Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 一个简单的读写大型输入文件问题_C#_Regex - Fatal编程技术网

C# 一个简单的读写大型输入文件问题

C# 一个简单的读写大型输入文件问题,c#,regex,C#,Regex,作为标题,我试图将字符之间的2个或更多空格替换为单个空格。但是,以下代码不适用于非常大的输入文件。我怎样才能使它也适用于巨大的输入文件 static void Main(string[] args) { Regex pattern = new Regex(@"[ ]{2,}"); //Pattern = 2 or more space in a string. StreamReader reader = new StreamReader(@"C:

作为标题,我试图将字符之间的2个或更多空格替换为单个空格。但是,以下代码不适用于非常大的输入文件。我怎样才能使它也适用于巨大的输入文件

  static void Main(string[] args)
    {
        Regex pattern = new Regex(@"[ ]{2,}");   //Pattern = 2 or more space in a string.

        StreamReader reader = new StreamReader(@"C:\CSharpProject\in\abc.txt");
        string content = reader.ReadToEnd();
        reader.Close();

        content = pattern.Replace(content, @" ");   //Replace 2 or more space into a single space.
        StreamWriter writer = new StreamWriter(@"C:\CSharpProject\out\abc.txt");
        writer.Write(content);
        writer.Close();
    }

一行一行,像这样:

static void Main(string[] args)
{
    Regex pattern = new Regex(@"[ ]{2,}");   //Pattern = 2 or more space in a string.

    using (StreamReader reader = new StreamReader(@"C:\CSharpProject\in\abc.txt"))
    using (StreamWriter writer = new StreamWriter(@"C:\CSharpProject\out\abc.txt"))
    {
       string content;
       while (null != (content = reader.ReadLine()));
          writer.WriteLine (pattern.Replace (content, " "));

       writer.Close();
       reader.Close();
    }
}

正在一次读取所有文件。这是有限度的。使用reader.ReadLine()代替reader.ReaderToEnd(),一次读取并处理一行文件。或者,如果文件没有“行”,请将输入文件分块读取,并在处理时保存输出块。

如果可能,您肯定不希望将整个文件读入字符串。流的全部意义在于,您可以一次处理一个位—您不想将4GB文件加载到RAM中,只是为了方便地将其当作字符串处理。您真的需要使用正则表达式吗?您可以读取文件(逐字符)并使用bool开关来确定是否保留空格char。这段代码不会丢失换行符吗
ReadLine
不返回行分隔符,您正在使用
Write
@CodeInChaos,oops。我的初稿做错了,但还是抓住了。谢谢,它能用。但是我必须用一个右括号替换分号:while(null!=(content=reader.ReadLine());这段代码的一个副作用是它替换了行尾。