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();

Answers


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

Need Your Help

Dynamics AX 4.0 Export Forms

export axapta x++

I created a method to export AOT (application object tree) Objects.

jquery :lt(10) on multiple blocks

javascript jquery

I've 3 blocks of ul.filter each one of them has varied amount of li from 20-40. I'd like to only show first 10 from each block. :lt(10) works in a strange way, revealing 10 from first block, but hi...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.