亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在非常大的文件 C# 的所有行上循環

在非常大的文件 C# 的所有行上循環

C#
慕蓋茨4494581 2021-11-28 19:45:42
我想循環使用一個非常大的文件(例如 10GB)的所有行 foreach我目前正在使用File.ReadLines這樣的:var lines = File.ReadLines(fileName);foreach (var line in lines) {  // Process line}但是如果文件大于 2MB,這會非常慢,并且循環會非常緩慢。如何循環處理非常大的文件?任何幫助,將不勝感激。
查看完整描述

2 回答

?
茅侃侃

TA貢獻1842條經驗 獲得超21個贊

你這樣做的方式是最好的方式,因為

  • 您不想一次將整個文件讀入 RAM

  • 您的線路處理獨立于以前的線路

抱歉,從硬盤讀取內容很慢。

改進可能來自其他來源:

  • 將您的文件存儲在更快的設備(SSD?)

  • 獲得更多 RAM 以將文件讀入內存以至少加快處理速度


查看完整回答
反對 回復 2021-11-28
?
千巷貓影

TA貢獻1829條經驗 獲得超7個贊

首先,您需要讀取整個文件還是僅讀取文件的一部分。


如果您只需要讀取文件的部分


const int chunkSize = 1024; // read the file by chunks of 1KB

using (var file = File.OpenRead("yourfile"))

{

    int bytesRead;

    var buffer = new byte[chunkSize];

    while ((bytesRead = file.Read(buffer, 0 /* start offset */, buffer.Length)) > 0)

    {

        // TODO: Process bytesRead number of bytes from the buffer

        // not the entire buffer as the size of the buffer is 1KB

        // whereas the actual number of bytes that are read are 

        // stored in the bytesRead integer.

    }

}

如果需要將整個文件加載到內存中。


重復使用此方法而不是直接加載到內存中,因為您可以控制正在執行的操作,并且可以隨時停止該過程。


或者您可以使用https://msdn.microsoft.com/en-us/library/system.io.memorymappedfiles.memorymappedfile.aspx?f=255&MSPPError=-2147217396MemoryMappedFile


內存映射文件將提供從內存訪問的程序視圖,但它只會第一次從磁盤加載。


long offset = 0x10000000; // 256 megabytes

long length = 0x20000000; // 512 megabytes


// Create the memory-mapped file.

using (var mmf = MemoryMappedFile.CreateFromFile(@"c:\ExtremelyLargeImage.data", FileMode.Open,"ImgA"))

{

     // Create a random access view, from the 256th megabyte (the offset)

     // to the 768th megabyte (the offset plus length).

     using (var accessor = mmf.CreateViewAccessor(offset, length))

     {

         //Your process

     }

}


查看完整回答
反對 回復 2021-11-28
  • 2 回答
  • 0 關注
  • 221 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號