【发布时间】:2017-07-06 09:19:17
【问题描述】:
我是 C# 和面向对象编程的新手。我有一个解析文本文件的应用程序。
应用程序的目标是读取提供的文本文件的内容并替换匹配的值。
当提供大约 800 MB 到 1.2GB 的文件作为输入时,应用程序崩溃并出现错误 System.OutofMemoryException。
在研究过程中,我遇到了几个建议将 Target Platform: 更改为 x64 的答案。
更改目标平台后也存在同样的问题。
以下是代码:
// Reading the text file
var _data = string.Empty;
using (StreamReader sr = new StreamReader(logF))
{
_data = sr.ReadToEnd();
sr.Dispose();
sr.Close();
}
foreach (var replacement in replacements)
{
_data = _data.Replace(replacement.Key, replacement.Value);
}
//Writing The text File
using (StreamWriter sw = new StreamWriter(logF))
{
sw.WriteLine(_data);
sw.Dispose();
sw.Close();
}
错误指向
_data = sr.ReadToEnd();
replacements 是一本字典。 Key 包含原始单词,Value 包含要替换的单词。
Key 元素被 KeyValuePair 的 Value 元素替换。
遵循的方法是读取文件,替换和写入。
我尝试使用 StringBuilder 代替字符串,但应用程序崩溃了。
可以通过一次读取一行文件、替换和写入来克服这个问题吗?做同样的事情的有效和更快的方法是什么。
更新:系统内存为 8 GB,在监控性能时,内存使用率达到 100%。
@Tim Schmelter 的回答效果很好。
但是,内存利用率飙升超过 90%。这可能是由于以下代码:
String[] arrayofLine = File.ReadAllLines(logF);
// Generating Replacement Information
Dictionary<int, string> _replacementInfo = new Dictionary<int, string>();
for (int i = 0; i < arrayofLine.Length; i++)
{
foreach (var replacement in replacements.Keys)
{
if (arrayofLine[i].Contains(replacement))
{
arrayofLine[i] = arrayofLine[i].Replace(replacement, masking[replacement]);
if (_replacementInfo.ContainsKey(i + 1))
{
_replacementInfo[i + 1] = _replacementInfo[i + 1] + "|" + replacement;
}
else
{
_replacementInfo.Add(i + 1, replacement);
}
}
}
}
//Creating Replacement Information
StringBuilder sb = new StringBuilder();
foreach (var Replacement in _replacementInfo)
{
foreach (var replacement in Replacement.Value.Split('|'))
{
sb.AppendLine(string.Format("Line {0}: {1} ---> \t\t{2}", Replacement.Key, replacement, masking[replacement]));
}
}
// Writing the replacement information
if (sb.Length!=0)
{
using (StreamWriter swh = new StreamWriter(logF_Rep.txt))
{
swh.WriteLine(sb.ToString());
swh.Dispose();
swh.Close();
}
}
sb.Clear();
它找到进行替换的行号。是否可以使用 Tim 的代码来捕获,以避免将数据多次加载到内存中。
【问题讨论】:
-
请更新您的帖子以包含日志文件的前几行。你的机器有多少内存?
-
那为什么不逐行阅读呢?
-
逐行读取,现在您将整个文件数据放入内存中,如果文件大小大于机器内存,则会导致失败
-
更新帖子
标签: c# dictionary system.io.file