c#文件流操作

       文件流保存数据!

   //定义一个字符串:

  string msg = "我是中国人,我爱中国,我是中国人,我爱中国,我是中国人,我爱中国,我是中国人,我爱中国,我是中国人,我爱中国";

  

  byte[] bytes=System.Text.Encoding.UTF8.GetBytes(msg);  //把字符串转换成byte数组,

 using( FileStream fswrite = new FileStream(@"c:\ddd.txt",FileMode.Create))   //创建一个文件流,创建一个文件ddd.txt保存在c盘根目录下;

{

  

   fswrite.Write(bytes ,0,bytes .Length );    //读入流,第一个参数传一个byte数组,第二个参数从byte数组的0开始读取,第三个一次读的长度

}

  读取文件流

  

using (FileStream fsread = new FileStream(@"c:\ddd.txt", FileMode.Open))  //读取一个本地的文件
{
    byte[] byts = new byte[1024];           

     int r = fsread.Read(byts,0,byts.Length );


     string msg = System.Text.Encoding.UTF8.GetString(byts);

     Console.WriteLine(msg);
     Console.ReadKey();
}

  大文件读取

    

  string source = @"E:\学习资料\C#本质论(中文版).pdf";

   string target = @"C:\01.pdf";

   FileCopy(source, target);

    

private static void FileCopy(string source, string target)
{
     //1.创建一个读取源文件的文件流
     using (FileStream fsRead = new FileStream(source, FileMode.Open))
    {
      long length = fsRead.Length;
      using (FileStream fsWrite = new FileStream(target, FileMode.Create))
      {
        //缓冲区。
       byte[] byts = new byte[1024 * 1024];
      long count = 0;
       while (true)
     {
         / /fsRead.Position
      //每次从文件流中读取2M的数据到byts中。
       int r = fsRead.Read(byts, 0, byts.Length);
        if (r <= 0)
      {
       break;
      }
      count += r;

      fsWrite.Write(byts, 0, r); //r表示向流中写入,本次实际读取到的字节个数。


     Console.Write(".");
     Console.WriteLine((double)count / length);
       }
     } 
   }
}

  

原文地址:https://www.cnblogs.com/xu3593/p/3036738.html