3

我现在正在研究一个允许编辑非常大的文本文件(4Gb+)的类。好吧,这听起来可能有点愚蠢,但我不明白如何修改流中的文本。这是我的代码:

public long  Replace(String text1, String text2)
{
    long replaceCount = 0;
    currentFileStream = File.Open(CurrentFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None);

    using (BufferedStream bs = new BufferedStream(currentFileStream))
    using (StreamReader sr = new StreamReader(bs))  
    {
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            if (line.Contains(text1))
            {
                line.Replace(text1, text2);

                // Here I should save changed line
                replaceCount++;
            }
        }
    }
    return replaceCount;
}
4

1 回答 1

1

您不会在代码中的任何地方替换它。您应该保存所有文本,然后将其再次写入文件。喜欢,

  public long  Replace(String text1, String text2)
 {
  long replaceCount = 0;
   currentFileStream = File.Open(CurrentFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
StringBuilder sb = new StringBuilder();
using (BufferedStream bs = new BufferedStream(currentFileStream))
using (StreamReader sr = new StreamReader(bs))  
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        string textToAdd = line;
        if (line.Contains(text1))
        {
            textToAdd = line.Replace(text1, text2);

            // Here I should save changed line
            replaceCount++;
        }
        sb.Append(textToAdd);
    }
}
using (FileStream fileStream = new FileStream(filename , fileMode, fileAccess))
        {
            StreamWriter streamWriter = new StreamWriter(fileStream);
            streamWriter.Write(sb.ToString());
            streamWriter.Close();
            fileStream.Close();
        }
return replaceCount;

}

于 2013-07-25T17:03:31.177 回答