how to change a line in a txt-document

Oct 31 2012 1:08 PM
Hi there, I'm having a problem here. I have a .txt-file where one line contains "<message>", this is the line I wanna change. But I can't get this code to work, anyone that can help me?
I have this code here that is working for only replacing a string, but I don't know how to do it so it changes the whole line.

public void t()
        {
            string filename = @"F:\test\test.txt";
            StringBuilder result = new StringBuilder();

            if (System.IO.File.Exists(filename))
            {
                using (StreamReader streamReader = new StreamReader(filename))
                {
                    String line;
                    while ((line = streamReader.ReadLine()) != null)
                    {
                        string newLine = String.Concat(line, Environment.NewLine);
                        newLine = newLine.Replace("<message>", "HEJHEJ ");
                        result.Append(newLine);
                    }
                }
            }

            using (FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite))
            {
                StreamWriter streamWriter = new StreamWriter(fileStream);
                streamWriter.Write(result);
                streamWriter.Close();
                fileStream.Close();
            }
        }

This code is changeing "<message>" to "HEJHEJ", but I want to whole line in the txt-document to change to "HEJHEJ", not just only "<message>"

Answers (4)