简体   繁体   中英

Appending text in C#

When changing the method to AppendText eg writeout.AppendText(firstline) I get StreamWriter does not support...

StreamWriter writeout = new StreamWriter(path);
        writeout.WriteLine(firstline);
        writeout.Close();

Instead of overwriting existing data in the text file, I want writeout to append "firstline" to the file

Change StreamWriter writeout = new StreamWriter(path); to StreamWriter writeout = new StreamWriter(path, true); .

See http://msdn.microsoft.com/en-us/library/aa328969%28v=vs.71%29.aspx .

Alternatively you can use File.AppendText , eg StreamWriter writeout = File.AppendText(path) .

Or even just File.AppendAllText , eg File.AppendAllText(path, firstline) .

You should create your StreamWriter with the explicit option to be able to APPEND to the file. Otherwise, it will always create a new one. Trying to call Append, when the StreamWriter wasn't created to append, gives the error you describe.

I'm not entirely sure, but I think you can do:

StreamWriter writeout = new StreamWriter(path, true);

to give the StreamWriter the ability to append.

Hope this helps.

您可以使用StreamWriter构造函数的第二个参数。
StreamWriter writeout = new StreamWriter(path, true);

使用构造函数StreamWriter writeout = new StreamWriter(path, true);

StreamWriter writeout = new StreamWriter(path,true); //true indicates appending
        writeout.WriteLine(firstline);
        writeout.Close();

使用附加的布尔参数创建StreamWriter,该布尔参数指定是否附加到现有文件:

StreamWriter writeout = new StreamWriter(path, true);

首先通过将StreamWriter.BaseStream.Position设置为流的末尾,找到流的末尾,然后照常继续。

What about using this?

var lines = new List<string>();
// load lines
System.IO.File.AppendAllLines(path, lines);
try
{
    StringBuilder sb = new StringBuilder();
    StreamReader sr = new StreamReader(Path);
    sb.AppendLine(sr.ReadToEnd());
    sb.AppendLine("= = = = = =");
    sb.AppendLine(fileName + " ::::: " + time);
    sr.Dispose();
    if (sw == null)
    {
        sw = new StreamWriter(Path);
    }
    sw.Write(sb.ToString());
    sw.Dispose();

}
catch (Exception e)
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM