我有 C# 代码来删除传入文本文件中的非 ASCII 字符,然后输出到 .NonAsciiChars 文本文件。 因为传入的文件是 XML 格式,返回方法可能是 LF ONLY 或 CRLF,所以我没有逐行替换(我使用的是 StreamReader.ReadToEnd())
现在的问题是当传入的文件很大(大约 2 GB)大小时,我收到以下错误。在我的案例中有没有更好的方法来删除非 ASCII 字符?传入的文件也会发送大约 4GB,恐怕到那时,读取部分也会出现 OutOfMemoryException。
非常感谢。
DateTime:2014-08-04 12:55:26,035 Thread ID:[1] Log Level:ERROR Logger Property:OS_fileParser.Program property:[(null)] - Message:System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
at System.Text.StringBuilder.ExpandByABlock(Int32 minBlockCharCount)
at System.Text.StringBuilder.Append(Char* value, Int32 valueCount)
at System.Text.StringBuilder.Append(Char[] value, Int32 startIndex, Int32 charCount)
at System.IO.StreamReader.ReadToEnd()
at OS_fileParser.MyProgram.FormatXmlFile(String inFile) in D:\Test\myProgram.cs:line 530
at OS_fileParser.MyProgram.Run() in D:\Test\myProgram.cs:line 336
myProgram.cs line 530: content = Regex.Replace(content, pattern, "");
myProgram.cs line 336: which is the point call the following method
const string pattern = @"[^\x20-\x7E]";
string content;
using (var reader = new StreamReader(inFile))
{
content = reader.ReadToEnd();
reader.Close();
}
content = Regex.Replace(content, pattern, "");
using (var writer = new StreamWriter(inFile + ".NonAsciiChars"))
{
writer.Write(content);
writer.Close();
}
using (var myXmlReader = XmlReader.Create(inFile + ".NonAsciiChars", myXmlReaderSettings))
{
try
{
while (myXmlReader.Read())
{
}
}
catch (XmlException ex)
{
Logger.Error("Validation error: " + ex);
}
}
最佳答案
您遇到 OutOfMemoryException
。为了节省内存,您可以按部分处理文件,here是一个很好的例子,说明如何逐行处理文件和 here是按字节,使用缓冲区(按1字节读取很慢)。
最简单的情况是这样的:
string line;
using (var reader = new StreamReader(inFile))
using (var writer = new StreamWriter(inFile + ".NonAsciiChars"))
while ((line = reader.ReadLine()) != null)
{
... // code to process line
writer.Write(line);
}
关于c# - 有没有更好的方法来替换 C# 中的非 ascii 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25121754/