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 也可


本文来自CSDN博客:http://blog.csdn.net/fox000002/archive/2010/10/23/5961337.aspx

发布了36 篇原创文章 · 获赞 0 · 访问量 7万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章