Question

I'm trying to get my streamwriter to add text onto the end of the text file but for some reason, it is just replacing the text with whatever I have entered. Any help is appreciated to fix this.

StreamWriter sw = new StreamWriter(Server.MapPath("~") + "/App_Data/blogMessages.txt");
sw.WriteLine(postTextBox.Text);
sw.Close();
Was it helpful?

Solution

you can use a over ridden method for stream writer

StreamWriter sw = new StreamWriter(Server.MapPath("~") + "/App_Data/blogMessages.txt", true);

this will apppend your text

OTHER TIPS

You need to use the overload version of the StreamWriter constructor that take an extra parameter to configure overwrite or append to the stream. And please add the using statement

using(StreamWriter sw = new StreamWriter(Server.MapPath("~") + 
                        "/App_Data/blogMessages.txt", true))
{

     sw.WriteLine(postTextBox.Text);

}

The using statement allows for the correct close and dispose of the stream also in case you get an exception when opening or writing

try this

 using (System.IO.TextWriter tw = new System.IO.StreamWriter(@"D:\TEMP\IEALog\path.txt", true))
        {
            tw.WriteLine(message + "Source ;- " + source + "StackTrace:- " + exc.StackTrace.ToString());
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top