0

I have huge text file say of 8 GB, need to replace some specific lines in it. I have found the lines and also replaced them. But the problem is I am rewriting each line to file. Just want to replace a line without rewriting complete file again. The text file contains Base64 string written line by line.I am reading the file line by line and whenever match found want to replace only the current line (Without creating another text file or rewriting all text in file) .Any help would be greatly appreciated. Using the below code. Each line is being read and written again however I am replacing only one file. See code below.

string originalFile =  "Original.txt";
string tempFile = "temp.txt";
string binayString = "base64string";
using (StreamWriter file2 = new StreamWriter(System.IO.File.Open(tempFile, FileMode.Create, FileAccess.Write)))
{
    StreamReader sr = new StreamReader(originalFile);
    String line = string.Empty;
    while ((line = sr.ReadLine()) != null)
    {
         if (line.StartsWith("Somestartpoint")
         {
           file2.WriteLine("Somestartpoint" + binayString);
           continue;
         }
         file2.WriteLine(line);
     }
     sr.Dispose();
}
System.IO.File.Replace(tempFile, originalFile, "backup.txt");
System.IO.File.Delete(checkPath + "backup.txt");
Ajinder Singh
  • 532
  • 2
  • 8
  • I have a single file and i don't want to rewrite the file text to another file (i.e temp file) and then replace with the source file . It is working like that but taking 3-4 minutes to rewrite all the text again . I just want to replace the specific line in file without rewriting or replacing its content to another file . – Ajinder Singh Apr 08 '14 at 13:00
  • I am writing Base64 strings line by line in Text file and then reading each line one by one . The replacement string is of same length but i don't know how to do it in c# ? – Ajinder Singh Apr 08 '14 at 13:11
  • A possible starting point for your problem is knowing the exact position of the streamreader when you try to read the line to replace. [Look at this question](http://stackoverflow.com/questions/10189270/tracking-the-position-of-the-line-of-a-streamreader) – Steve Apr 08 '14 at 13:15
  • I got the line to be replaced. – Ajinder Singh Apr 08 '14 at 13:23
  • But to replace this line I need to write all lines to temp file and then replace the file. – Ajinder Singh Apr 08 '14 at 13:32
  • Well, the idea is: if you are sure that the line is exactly the same lenght and you know where it starts, then you could use some binary writer to position on the exact spot where the line starts and write binary data there – Steve Apr 08 '14 at 13:36

0 Answers0