当前位置: 首页 > news >正文

C# 文件读取

        文件读取是指使用 C# 程序从计算机文件系统中获取文件内容的过程。将存储在磁盘上的文件内容加载到内存中,供程序处理。主要类型有:文本文件读取(如 .txt, .csv, .json, .xml);二进制文件读取(如 .jpg, .png, .exe)。

同步方法

File 

ReadAllText

是 C# 中一个简单易用的文件写入方法,它会创建新文件,如果文件已存在则覆盖。

string path = @"D:\CSharpProject\File\MyTest.txt";
string str = File.ReadAllText(path);

 ReadLines

获取文件中每行数据组成的集合

string path = @"D:\CSharpProject\File\MyTest.txt";
var list = File.ReadLines(path).ToList();
Console.WriteLine(string.Join(",", list));

ReadAllLines

会一次性将整个文本文件的所有行读取到一个字符串数组中。

string path = @"D:\CSharpProject\File\MyTest.txt";
string[] list = File.ReadAllLines(path);
Console.WriteLine(string.Join(",", list));

ReadAllBytes

一个用于读取二进制文件的方法,它会将整个文件内容读取到一个字节数组中。

string path = @"D:\CSharpProject\File\MyTest.txt";
byte[] str = File.ReadAllBytes(path);

StreamReader

StreamReader 是 System.IO 命名空间中的一个类,专门用于从流(如文件流)中读取字符数据。它提供了高效的文本读取能力,特别适合处理大型文本文件。

方法描述
Read()读取下一个字符
ReadLine()读取一行字符
ReadToEnd()读取从当前位置到流末尾的所有内容

简单使用

string path = @"D:\CSharpProject\File\MyTest.txt";
using (StreamReader reader = new StreamReader(path))
{string content = reader.ReadToEnd();Console.WriteLine(content);
}

逐行读取

using (StreamReader reader = new StreamReader("data.txt"))
{string line;while ((line = reader.ReadLine()) != null){Console.WriteLine(line);}
}

读取特定数量字符

char[] buffer = new char[100];
using (StreamReader reader = new StreamReader("file.txt"))
{int charsRead = reader.Read(buffer, 0, buffer.Length);string result = new string(buffer, 0, charsRead);
}

FileStream 

         FileStream 是 System.IO 命名空间中的一个类,提供了对文件进行低级读写操作的能力。与更高级的 StreamReader/StreamWriter 相比,FileStream 提供了更底层的控制,适合处理二进制文件或需要精细控制文件操作的场景。

using System.IO;string filePath = "example.bin";// 使用 using 语句确保资源被正确释放
using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{byte[] buffer = new byte[fileStream.Length];int bytesRead = fileStream.Read(buffer, 0, buffer.Length);Console.WriteLine($"读取了 {bytesRead} 字节");// 处理 buffer 中的数据...
}

异步方法

File 

ReadAllTextAsync

是ReadAllText的异步实现,功能相同,不会阻塞主线程。

using System.IO;
using System.Threading.Tasks;public async Task<string> ReadFileContentAsync(string filePath)
{return await File.ReadAllTextAsync(filePath);
}

ReadAllLinesAsync

是ReadAllLines的异步实现,功能相同,不会阻塞主线程。

using System.IO;
using System.Threading.Tasks;public async Task<string[]> ReadFileAsync(string filePath)
{return await File.ReadAllLinesAsync(filePath);
}

ReadAllBytesAsync

是ReadAllBytes的异步实现,功能相同,不会阻塞主线程

using System.IO;
using System.Threading.Tasks;public async Task<byte[]> ReadBinaryFileAsync(string filePath)
{return await File.ReadAllBytesAsync(filePath);
}

StreamReader

 简单使用

using System.IO;
using System.Threading.Tasks;async Task<string> ReadFileAllTextAsync(string filePath)
{using (StreamReader reader = new StreamReader(filePath)){return await reader.ReadToEndAsync();}
}

异步逐行读取文件

using (StreamReader reader = new StreamReader("data.txt"))
{string line;while ((line = reader.ReadLine()) != null){Console.WriteLine(line);}
}

异步读取指定数量字符

async Task<string> ReadChunkAsync(string path, int chunkSize)
{using (var reader = new StreamReader(path)){char[] buffer = new char[chunkSize];int bytesRead = await reader.ReadBlockAsync(buffer, 0, chunkSize);return new string(buffer, 0, bytesRead);}
}

FileStream 

using System.IO;
using System.Threading.Tasks;async Task<byte[]> ReadFileFullyAsync(string filePath)
{using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, FileOptions.Asynchronous)) // 关键选项{byte[] buffer = new byte[fs.Length];await fs.ReadAsync(buffer, 0, buffer.Length);return buffer;}
}

对比

方法特点适用场景内存效率异步支持典型文件大小
File.ReadAllText一次性读取全部文本小文本文件处理<10MB
File.ReadAllTextAsync异步读取全部文本UI应用读取小文本<10MB
File.ReadAllLines按行读取为数组需要行处理的小文件<10MB
File.ReadAllLinesAsync异步按行读取UI应用需要行处理<10MB
File.ReadAllBytes读取二进制数据图片/音频等二进制文件<50MB
File.ReadAllBytesAsync异步读取二进制UI应用处理二进制<50MB
File.ReadLines延迟行迭代大文本文件处理10MB+
StreamReader灵活文本读取需要控制读取过程有(Async方法)任意大小
FileStream底层二进制读取大文件/随机访问任意大小

选择参考

参考项

推荐方法

场景举例

小文本文件处理 ( < 1MB )

ReadAllText 

ReadAllTextAsync

ReadAllLines 

ReadAllLinesAsync

配置文件读取

小型JSON/XML文件解析

模板文件加载

大文本文件处理 ( > 10MB )

File.ReadLines (LINQ兼容)

StreamReader (逐行处理)

StreamReader.ReadLineAsync (异步逐行)

日志文件分析

大型CSV数据处理

文本文件实时监控

二进制文件处理

File.ReadAllBytes / ReadAllBytesAsync (小文件)

FileStream (大文件)

图片/音视频处理

文件加密/解密

自定义二进制格式解析

同步和异步选择

  1. 使用同步方法

    • 简单的控制台应用程序

    • 需要简单快速完成的小文件操作

    • 在后台线程中执行的文件操作

  2. 使用异步方法

    • UI应用程序(避免界面冻结)

    • Web应用程序和服务(提高并发处理能力)

    • 大文件操作(避免阻塞主线程)

    • 需要响应性的应用程序

http://www.xdnf.cn/news/102187.html

相关文章:

  • 极狐GitLab 的压缩和合并是什么?
  • AI赋能社区生态:虎跃办公的网址导航革新实践
  • 一 、环境的安装 Anaconda + Pycharm + PaddlePaddle
  • Execl 最佳字体和大小推荐[特殊字符]
  • 状态空间方程 —— 极点配置
  • 域名 → IP 的解析全过程
  • python异步协程async调用过程图解
  • Linux[指令与权限]
  • ZYNQ笔记(十三):双核 AMP 通信实验
  • 星火燎原:Spark技术如何重塑大数据处理格局
  • 8. kubernetes的service原理
  • MySQL 8 自动安装脚本(CentOS-7 系统)
  • 【哈希表】1399. 统计最大组的数目
  • 从零开始搭建Django博客③--前端界面实现
  • 如何批量为多张图片(JPG、PNG、BMP、WEBP 等格式)添加自定义水印保护
  • ApacheJmeter使用权威指南
  • 【AI】Trae的MCP配置及使用测试
  • 在统信UOS/麒麟Kylin OS操作系统中配置APT和GIT代理
  • 【论文阅读25】-滑坡时间预测-PFTF
  • 时分复用、频分复用和码分复用简要比较分析
  • Linux进程调度
  • AI PPT创作原理解析:让你的演示文稿更智能
  • Python内置函数---breakpoint()
  • 《算法笔记》10.4小节——图算法专题->最短路径 问题 D: 最短路径
  • JavaScript 中改变 this 指向的方法
  • Python 绘图代码解析:用 Turtle 和 Colorsys 打造绚丽图案
  • sde启动报错:Unable to initialize sockets for listening(-102).
  • 基于STM32_HAL库的HC-08蓝牙插座项目
  • C++:多态
  • UnoCSS原子CSS引擎-前端福音