user987316
user987316

Reputation: 942

Override line in file while writing

I am reading a file using streamreader opened in ReadWrite mode. The requirement I have is to check for a file for specific text, and if it is found, replace that line with a new line.

Currently I have initialized a StreamWriter for writing.

It is writing text to a file but it's appending that to a new line.

So what should I do to replace the particular line text?

System.IO.FileStream oStream = new System.IO.FileStream(sFilePath, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.Read); 
System.IO.FileStream iStream = new System.IO.FileStream(sFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite); 

System.IO.StreamWriter sw = new System.IO.StreamWriter(oStream);
System.IO.StreamReader sr = new System.IO.StreamReader(iStream); 

string line;
int counter = 0;
while ((line = sr.ReadLine()) != null)
{
    if (line.Contains("line_found"))
    {
        sw.WriteLine("line_found false");
        break;
    }
    counter++;
}
sw.Close();
sr.Close();

Upvotes: 0

Views: 772

Answers (1)

Pandian
Pandian

Reputation: 9126

Hi Try the below Code.... it will help you....

//Replace all the HI in the Text file...

var fileContents = System.IO.File.ReadAllText(@"C:\Sample.txt");

fileContents = fileContents.Replace("Hi","BYE"); 

System.IO.File.WriteAllText(@"C:\Sample.txt", fileContents);

//Replace the HI in a particular line....

        string[] lines = System.IO.File.ReadAllLines("Sample.txt");
        for (int i = 0; i < lines.Length; i++)
        {
            if(lines[i].Contains("hi"))
            {
                MessageBox.Show("Found");
                lines[i] = lines[i].Replace("hi", "BYE");
                break;
            }
        }
        System.IO.File.WriteAllLines("Sample.txt", lines);

Upvotes: 3

Related Questions