使用FileStream向txt格式的文本文件 "追加" 新内容并读取

本文介绍了一个使用C#进行文件读写的示例程序。该程序首先定义了文件路径,然后通过FileStream对象实现了文件的读取和写入操作。在写入过程中,程序将字符串Hello,World!转换为字节并追加到文件末尾;在读取过程中,程序将文件内容转换回字符串并输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

复制代码
 1 //得到文件路径。
 2 static string filePath = AppDomain.CurrentDomain.BaseDirectory+"\\TxtFile.txt";
 3 static void Main(string[] args)
 4 {
 5   //调用写入方法。
 6    WriteTxtFile(filePath);
 7    //调用读取方法。
 8    Console.WriteLine(ReadTxtFile(filePath));           
 9    Console.Read();
10 }
11 
12 /// <summary>
13 /// 此方法用于读取文件。
14 /// </summary>
15 /// <param name="_filePath">读取文件的路径。</param>
16 /// <returns></returns>
17 static string ReadTxtFile(string _filePath)
18 {
19    //result:用于得到从txt文件中读取到的内容。
20    string result;
21    //创建一个FileStream对象。
22    using (FileStream fs = new FileStream(_filePath, FileMode.Open))
23    {
24      //声明一个字节数组,其长度等于读取到的文件的长度。
25       byte[] bytes = new byte[fs.Length];
26       //读取txt文件中的内容。r代表实际读取到的有效字节数。
27       int r = fs.Read(bytes, 0, bytes.Length);
28       //将读取到的文件转换为字符串后赋值给result。
29       result = Encoding.UTF8.GetString(bytes, 0, r);
30     }
31     return result;
32 }
33 
34 /// <summary>
35 /// 此方法用于往txt文件中写入数据。
36 /// </summary>
37 /// <param name="_filePath">写入文件的路径。</param>
38 static void WriteTxtFile(string _filePath)
39 {
40   //创建一个FileStream对象。
41    using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Write))
42    {
43      //将要追加的字符串转换成字节数组。
44       byte[] byteBuffer = Encoding.UTF8.GetBytes("Hello,World!");               
45       //设置当前流的位置(如果不设置下面的Position属性,执行Write方法的时候是从前往后覆盖)。
46       fs.Position = fs.Length;
47       //写入文件。
48       fs.Write(byteBuffer, 0, byteBuffer.Length);
49       Console.WriteLine("写入成功。");
50     }
51 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值