簡體   English   中英

如何從c#中的文本文件中獲取某些行?

[英]How to obtain certain lines from a text file in c#?

我在C#工作,我有一個大文本文件(75MB)我想保存與正則表達式匹配的行

我嘗試使用streamreader和ReadToEnd讀取文件,但它需要400MB的內存

並在再次使用時創建內存不足異常。

然后我嘗試使用File.ReadAllLines():

string[] lines = File.ReadAllLines("file");

StringBuilder specialLines = new StringBuilder();


foreach (string line in lines)

 if (match reg exp)

  specialLines.append(line);

這一切都很棒,但是當我的函數結束時,所采用的內存並沒有清除,我留下300MB的已用內存,只有在調用函數並執行行時:string [] lines = File.ReadAllLines(“file”); 我看到內存清理為50MB給予或接受然后重新分配回200MB

如何清除此內存或以不同的方式獲取我需要的行?

        var file = File.OpenRead("myfile.txt");
        var reader = new StreamReader(file);
        while (!reader.EndOfStream)
        {
            string line = reader.ReadLine();
            //evaluate the line here.
        }
        reader.Dispose();
        file.Dispose();

您需要流式傳輸文本,而不是將整個文件加載到內存中。 這是一種方法,使用擴展方法和Linq:

static class ExtensionMethods
{
    public static IEnumerable<string> EnumerateLines(this TextReader reader)
    {
        string line;
        while((line = reader.ReadLine()) != null)
        {
            yield return line;
        }
    }
}

...

var regex = new Regex(..., RegexOptions.Compiled);
using (var reader = new StreamReader(fileName))
{
    var specialLines =
        reader.EnumerateLines()
              .Where(line => regex.IsMatch(line))
              .Aggregate(new StringBuilder(),
                         (sb, line) => sb.AppendLine(line));
}

您可以使用StreamReader#ReadLine逐行讀取文件並保存所需的那些行。

您應該使用Enumerator模式來保持較低的內存占用,以防您的文件很大。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM