【C#】文件流和文本处理

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#文件流的基本方法。在实际应用中,你可能需要根据具体需求来选择合适的类和方法来处理文件流。

 

  • 15
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CN.LG

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值