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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章