C#之文件读写方式

在.NET中处理文件读写,你可以使用多种方式,包括使用System.IO命名空间下的类

File类、StreamReaderStreamWriter类、以及BinaryReaderBinaryWriter类,FileStream
适用场景选择:
  • ‌小到中等大小的文件‌:如果你正在处理的小文件(例如配置文件或日志文件),使用File.ReadAllText更为方便。

  • ‌大文件‌:对于大文件,使用StreamReader可以避免内存溢出问题,因为它允许你逐块读取文件内容。

  • ‌需要编码支持‌:如果你需要处理特定编码的文件(如UTF-8, UTF-16等),StreamReader提供了更多的灵活性和控制。

  • ‌性能考虑‌:如果内存使用是关键考虑因素(例如,在内存受限的环境中),使用StreamReader可能更合适。

一、使用File

File.ReadAllText方法非常简单,它一次性读取文件的全部内容到内存中的字符串。这对于小到中等大小的文件非常方便,因为它简单易用。

  • 代码简洁,易于理解和实现。

  • 适用于文件大小不是极端大的情况。

  • 不需要显式地打开和关闭流。

  • 1.写入文件

  • string path = @"C:\path\to\your\file.txt";

  • string content = "Hello, World!";

  • File.WriteAllText(path, content);

  • 2.读取文件 File.ReadAllText(path);

  • string path = @"C:\path\to\your\file.txt";

  • string content = File.ReadAllText(path);

  • Console.WriteLine(content);

二、使用StreamReaderStreamWriter

StreamReader类用于从流中读取字符,并支持多种编码方式。这对于大文件尤其有用,因为它允许你逐块读取文件内容,而不是一次性将整个文件加载到内存中

  • 适合处理大文件,因为它允许流式读取。

  • 提供了灵活的编码选项。

  • 使用using语句确保文件在使用后被正确关闭。

  • 1.写入文件

  • using (StreamWriter writer = new StreamWriter(@"C:\path\to\your\file.txt"))

  • {

  •     writer.WriteLine("Hello, World!");

  • }

  • 2.读取文件

  • using (StreamReader reader = new StreamReader(@"C:\path\to\your\file.txt"))

  • {

  •     string line;

  •     while ((line = reader.ReadLine()) != null)

  •     {

  •         Console.WriteLine(line);

  •     }

  • }

三、使用BinaryReaderBinaryWriter(用于二进制文件)
  • 1.写入二进制文件

  • using (BinaryWriter writer = new BinaryWriter(File.Open(@"C:\path\to\your\binaryfile.dat", FileMode.Create)))

  • {

  •     writer.Write(12345); // 写入整数

  •     writer.Write("Hello".ToCharArray()); // 写入字符串的字符数组

  • }

  • 2.读取二进制文件

  • using (BinaryReader reader = new BinaryReader(File.Open(@"C:\path\to\your\binaryfile.dat", FileMode.Open)))

  • {

  •     int number = reader.ReadInt32(); // 读取整数

  •     char[] chars = reader.ReadChars(5); // 读取字符串的字符数组,这里假定是5个字符长度的字符串"Hello"

  •     Console.WriteLine(new string(chars)); // 输出字符串

  • }

四、使用FileStream进行更灵活的操作
  • 1.写入文件

  • using (FileStream fs = new FileStream(@"C:\path\to\your\file.txt", FileMode.Create))

  • {

  •     byte[] info = new UTF8Encoding(true).GetBytes("Hello, World!");

  •     fs.Write(info, 0, info.Length);

  • }

  • 2.读取文件

  • using (FileStream fs = new FileStream(@"C:\path\to\your\file.txt", FileMode.Open))

  • {

  •     byte[] buffer = new byte[1024]; // 根据需要调整缓冲区大小

  •     int bytesRead;

  •     while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0)

  •     {

  •         Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, bytesRead));

  •     }

  • }

在使用文件操作时可能会遇到文件不存在、路径错误或权限问题。可以使用try-catch块来捕获并处理这些异常
  • 使用using语句可以确保即使在发生异常的情况下,文件也能被正确关闭。这是推荐的做法,因为它能自动调用对象的Dispose方法,释放资源。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值