C# 用記憶體對應檔讀取大記錄檔(.log)

來源:互聯網
上載者:User

C# 讀取大檔案的方法有很多,在這裡我使用的是File.ReadAllBytes(fileName)一次讀出來,再用MemoryStream放在記憶體,再用StreamReader一行行的讀出來,速度也挺快的,16M的文本大概也就8秒左右,算起來差不多算快了。不過還是不能滿足大檔案(畢竟記憶體空間有限)。

//using System.IO; 
//using System.Text;
//放入記憶體流,以便逐行讀取 
MemoryStream ms = new MemoryStream(File.ReadAllBytes(fileName));
using (StreamReader sr = new StreamReader(ms, Encoding.GetEncoding("GB2312")))
{
    try
    {
        while (sr.Peek() > -1)
        {
            string info = sr.ReadLine();

            //do something
        }
    }
    catch (Exception ex) { sr.Close(); throw ex; }
}
ms = null;

參考:http://www.cnblogs.com/criedshy/archive/2010/06/13/1757826.html

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.