Modify FileStream

浪子不回头ぞ 提交于 2021-02-09 11:58:47

问题


I'm working now on a class that will allow editing very big text files (4Gb+). Well it may sound a little stupid but I do not understand how I can modify text in a stream. Here is my code:

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;
}

回答1:


You are not replacing it anywhere in your code. You should save all the text and then write it again to the file. Like,

  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;

}



来源:https://stackoverflow.com/questions/17864254/modify-filestream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!