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();
有帮助吗?

解决方案

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

其他提示

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());
        }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top