[Exclusively for beginners] The FileStream object in c# reads and writes large files

When it comes to file streams , we have to talk about the following classes
: FileStream, MemoryStream, NetWorkStream, StreamReader, StreamWriter, TextReader, and TextWriter
. Before using these classes, let's first understand the uses and differences of these classes.

Commonly used file streams in C# (FileStream, StreamReader/Writer, MemoryStream)_c# filestream and streamwriter-CSDN blog

Read data:

FileStream fs = new FileStream(path,FileMode.Open);    //初始化文件流
byte[] arr = new byte[fs.Length];                      //初始化字节数组
fs.Read(arr, 0, arr.Length);                           //从流中数据读取到字节数组中
fs.Close();                                            //关闭流
string str = Encoding.UTF8.GetString(arr);             //将字节数组转换为字符串
Console.WriteLine(str);

data input

FileStream fs = new FileStream(path,FileMode.Append);  //初始化文件流
byte[] arr = Encoding.UTF8.GetBytes("程序人生道可道");   //将字符串转换为字节数组
fs.Write(arr,0,arr.Length);                            //将字节数组写入文件流
fs.Close(); 

Two: StreamReader/StreamWriter class

Purpose: Mainly used to process stream data. They provide efficient stream reading/writing functions respectively.
Advantages: You can directly read and write strings without converting them into byte arrays.
Note: For reading and writing text files, it is usually more convenient to use the StreamReader class and the StreamWriter class. The bottom layer is to read and write text files through FileStream.

Read data:
 

FileStream fs = new FileStream(path,FileMode.Open);  //初始化文件流
StreamReader sr = new StreamReader(fs);              //初始化StreamReader
string line = sr.ReadLine();                         //直接读取一行
string line = sr.ReadToEnd()                         //读取全文
sr.Close();                                          //关闭流
fs.Close();                                          //关闭流
Console.WriteLine(line);

After testing: when reading data, the order of closing sr and fs can be reversed, and the data can still be read. Considering the code specifications, conventional writing will do.

data input:

FileStream fs = new FileStream(path,FileMode.Append); //初始化文件流
StreamWriter sw = new StreamWriter(fs);               //初始化StreamWriter
sw.WriteLine("程序人生道可道");                         //写入一行数据
sw.Close();                                           //关闭流
fs.Close();                                           //关闭流

After testing: when writing data, fs must be closed after sw, otherwise an exception will be thrown (because you have closed the file stream before writing data, and the data will definitely not be written)

“` 
using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Reflection; 
using System.Text;

namespace IO目录管理 
{ 
class Program 
{ 
private string _StrSourcePath = @”E:\TestDir\Test\1.txt”; //源文件目录 
private string _StrTagrgetPath = @”F:\TestDir\Test\1.txt”; //目标文件目录

 public void Test()
  {
    //路径合法性判断
    if(File.Exists(_StrSourcePath))
    {
      //构造读取文件流对象
      using (FileStream fsRead = new FileStream(_StrSourcePath, FileMode.Open)) //打开文件,不能创建新的
      {
        //构建写文件流对象
        using (FileStream fsWrite = new FileStream(_StrTagrgetPath,FileMode.Create)) //没有找到就创建
        {
          //开辟临时缓存内存
          byte[] byteArrayRead = new byte[1024 * 1024]; // 1字节*1024 = 1k 1k*1024 = 1M内存

          //通过死缓存去读文本中的内容
          while(true)
          {
            //readCount 这个是保存真正读取到的字节数
            int readCount = fsRead.Read(byteArrayRead, 0, byteArrayRead.Length);

            //开始写入读取到缓存内存中的数据到目标文本文件中
            fsWrite.Write(byteArrayRead, 0, readCount);


            //既然是死循环 那么什么时候我们停止读取文本内容 我们知道文本最后一行的大小肯定是小于缓存内存大小的
            if(readCount < byteArrayRead.Length)
            {
              break; //结束循环
            }
          }
        }
      }
    }
    else
    {
      Console.WriteLine("源路径或者目标路径不存在。");
    }
  }


  static void Main(string[] args)
  {
    Program p = new Program();
    p.Test();

  }
}

}

Guess you like

Origin blog.csdn.net/zgscwxd/article/details/135246274