C# 读取文件方法集

C# 可以使用的 .Net 类库之庞大,不得不感慨一下。对于读取文件这一部分,可以使用的方法很多,特将想到和看到的方法收集在此,用到时可以查一查,温习一下。

 

以文本文件为例,可以有多种方法。

 

方法一:System.IO.File.ReadAllText

 

string content = System.IO.File.ReadAllText(fn);

 

方法二:Stream

 

        Stream stream = File.OpenRead(fn);
        int bytesToRead = 1024;
        int bytesRead = 0;
        byte[] buffer = new byte [bytesToRead];

        // Fill up the buffer repeatedly until we reach the end of file
        do {
            bytesRead = stream.Read(buffer, 0, bytesToRead);
            Console.Write(Encoding.ASCII.GetChars(buffer,0, bytesRead));
        } while (bytesToRead == bytesRead);
        stream.Close( );

 

方法三:TextReader

 

        TextReader reader = File.OpenText(fn);

        string line;
       
        // Read a line at a time until we reach the end of file
        while (reader.Peek() != -1) {
            line = reader.ReadLine();
            Console.WriteLine(line);
        }
        reader.Close();

 

方法四:StreamReader

 

        StreamReader sr = new StreamReader(fn);
        string content = sr.ReadToEnd();
        Console.WriteLine(content);
        sr.Close();
        // You should call Dispose on 'reader' here, too.
        sr.Dispose();

 


 

至于二进制文件,有 BinaryReader/BinaryWriter,当然用 FileStream 也可以。

 

 其他的方法或内容待以后不断补充。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值