【C#】文件流和文本处理
创始人
2024-11-11 08:07:02

1. 文件流的基本概念

文件流是C#中处理文件读写的抽象,它提供了对文件内容进行顺序访问的能力。在文件流中,数据按照字节或块的方式传输,而不受文件中数据的格式影响。文件流通常与System.IO命名空间中的类一起使用,包括FileStream、StreamReader和StreamWriter等。

2、使用FileStream类创建一个文件并写入数据:

using System; using System.IO;   class Program {     static void Main()     {         string path = @"C:\Temp\MyTest.txt";           // 使用FileMode.Create创建新文件,或者覆盖已有的文件         using (FileStream fs = new FileStream(path, FileMode.Create))         {             byte[] data = System.Text.Encoding.UTF8.GetBytes("This is some text");             // 写入数据到文件             fs.Write(data, 0, data.Length);         }     } }

3、读取文件流中的数据:

using System; using System.IO;   class Program {     static void Main()     {         string path = @"C:\Temp\MyTest.txt";           // 使用FileMode.Open打开已有的文件         using (FileStream fs = new FileStream(path, FileMode.Open))         {             byte[] data = new byte[1024];             int byteRead = fs.Read(data, 0, data.Length);             // 转换为字符串并显示             Console.WriteLine(System.Text.Encoding.UTF8.GetString(data, 0, byteRead));         }     } }

 

4、使用StreamReader和StreamWriter来读写文本文件:

 

using System; using System.IO;   class Program {     static void Main()     {         string path = @"C:\Temp\MyTest.bin";           // 使用BinaryWriter写入二进制数据         using (BinaryWriter bw = new BinaryWriter(File.Open(path, FileMode.Create)))         {             bw.Write("Hello World!");         }           // 使用BinaryReader读取二进制数据         using (BinaryReader br = new BinaryReader(File.Open(path, FileMode.Open)))         {             string result = br.ReadString();             Console.WriteLine(result);         }     } }

以上就是一些使用C#文件流的基本方法。在实际应用中,你可能需要根据具体需求来选择合适的类和方法来处理文件流。

 

相关内容

热门资讯

裸辞做“一人公司”,我后悔了 去年这个时候,一位以色列程序员正在东南亚旅行。他顺手把一个在脑子里转了很久的想法做成了产品,一个让任...
南京建成国内首个Pre-6G试... 4月21日,2026全球6G技术与产业生态大会在南京开幕。全息互动技术展台前,一名远在北京的工作人员...
超梵求职受邀参加“2025抖音... 超梵求职受邀参加“2025抖音巨量引擎成人教育行业生态大会”,探讨分享优质内容传播,服务万千学员。 ...
摩托罗拉Razr 2026(R... IT之家 4 月 22 日消息,摩托罗拉宣布新一代 Razr 折叠手机将于 4 月 29 日在美国发...
库克卸任,特纳斯领航:苹果新纪... 苹果首席执行官蒂姆·库克将卸任,硬件工程主管约翰·特纳斯将接任,苹果公司今天宣布此事。 库克将在夏季...