c# - 有没有更好的方法来替换 C# 中的非 ascii 字符

标签 c# regex

我有 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/

相关文章:

javascript - HTML5 文本字段的正则表达式模式

Java-在两个特殊字符之间提取字符串的一部分

c# - WP7.8 : Bound items in scrollbox updated with wrong data

c# - ASP.Net 中静态类的生命周期

c# - 如何使用 SQL 中的 LIKE 逻辑使用 c# 过滤字符串?

java - 将正则表达式 ruby​​ 转换为 java

javascript - 匹配某种字符串的正则表达式模式

c# - 单元测试 MongoWriteExceptions

c# - 计算两个日期之间的日历月数

java - 如何匹配任何单词但忽略以多个空格开头的单词?