Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify FileStream

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;
}
like image 368
Sergiu Cojocaru Avatar asked May 21 '26 16:05

Sergiu Cojocaru


1 Answers

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;

}

like image 71
Ehsan Avatar answered May 23 '26 05:05

Ehsan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!