简体   繁体   English

使用 StreamWriter 将行附加到文件

[英]Append lines to a file using a StreamWriter

I want to append lines to my file.我想将行附加到我的文件中。 I am using a StreamWriter:我正在使用 StreamWriter:

StreamWriter file2 = new StreamWriter(@"c:\file.txt");
file2.WriteLine(someString);
file2.Close();

The output of my file should be several strings below each other, but I have only one row, which is overwritten every time I run this code.我的文件的输出应该是几个字符串,但我只有一行,每次运行此代码时都会被覆盖。

Is there some way to let the StreamWriter append to an existing file?有没有办法让 StreamWriter 附加到现有文件?

Use this instead:改用这个:

new StreamWriter("c:\\file.txt", true);

With this overload of the StreamWriter constructor you choose if you append the file, or overwrite it.通过 StreamWriter 构造函数的重载,您可以选择是附加文件还是覆盖它。

C# 4 and above offers the following syntax, which some find more readable: C# 4 及更高版本提供以下语法,有些人认为这些语法更具可读性:

new StreamWriter("c:\\file.txt", append: true);
 using (FileStream fs = new FileStream(fileName,FileMode.Append, FileAccess.Write))
 using (StreamWriter sw = new StreamWriter(fs))
 {
    sw.WriteLine(something);
 }

I assume you are executing all of the above code each time you write something to the file.我假设您每次向文件写入内容时都在执行上述所有代码。 Each time the stream for the file is opened, its seek pointer is positioned at the beginning so all writes end up overwriting what was there before.每次打开文件的流时,它的查找指针都位于开头,因此所有写入最终都会覆盖之前的内容。

You can solve the problem in two ways: either with the convenient您可以通过两种方式解决问题:使用方便的

file2 = new StreamWriter("c:/file.txt", true);

or by explicitly repositioning the stream pointer yourself:或者自己显式地重新定位流指针:

file2 = new StreamWriter("c:/file.txt");
file2.BaseStream.Seek(0, SeekOrigin.End);

Try this:试试这个:

StreamWriter file2 = new StreamWriter(@"c:\file.txt", true);
file2.WriteLine(someString);
file2.Close();

Replace this:替换这个:

StreamWriter file2 = new StreamWriter("c:/file.txt");

with this:有了这个:

StreamWriter file2 = new StreamWriter("c:/file.txt", true);

true indicates that it appends text. true表示它附加文本。

Actually only Jon's answer (Sep 5 '11 at 9:37) with BaseStream.Seek worked for my case.实际上,只有 Jon 对 BaseStream.Seek 的回答(2011 年 9 月 5 日 9:37)适用于我的情况。 Thanks Jon!谢谢乔恩! I needed to append lines to a zip archived txt file.我需要附加到 zip 存档的 txt 文件。

using (FileStream zipFS = new FileStream(@"c:\Temp\SFImport\test.zip",FileMode.OpenOrCreate))
{
    using (ZipArchive arch = new ZipArchive(zipFS,ZipArchiveMode.Update))
    {
        ZipArchiveEntry entry = arch.GetEntry("testfile.txt");
        if (entry == null)
        {
            entry = arch.CreateEntry("testfile.txt");
        }
        using (StreamWriter sw = new StreamWriter(entry.Open()))
        {
            sw.BaseStream.Seek(0,SeekOrigin.End);
            sw.WriteLine("text content");
        }
    }
}

将此StreamWriter构造函数与第二个参数 - true

Another option is using System.IO.File.AppendText另一种选择是使用System.IO.File.AppendText

This is equivalent to the StreamWriter overloads others have given.这相当于其他人给出的 StreamWriter 重载。

Also File.AppendAllText may give a slightly easier interface without having to worry about opening and closing the stream.此外File.AppendAllText可能会提供一个稍微简单的界面,而不必担心打开和关闭流。 Though you may need to then worry about putting in your own linebreaks.尽管您可能需要担心放入自己的换行符。 :) :)

One more simple way is using the File.AppendText it appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist and returns a System.IO.StreamWriter一种更简单的方法是使用File.AppendText它将 UTF-8 编码的文本附加到现有文件,或者如果指定的文件不存在并返回System.IO.StreamWriter则附加到新文件

using (System.IO.StreamWriter sw = System.IO.File.AppendText(logFilePath + "log.txt"))
{                                                
    sw.WriteLine("this is a log");
}

Replace this line:替换这一行:

StreamWriter sw = new StreamWriter("c:/file.txt");

with this code:使用此代码:

StreamWriter sw = File.AppendText("c:/file.txt");

and then write your line to the text file like this:然后将您的行写入文本文件,如下所示:

sw.WriteLine("text content");

You can use like this你可以这样使用

 using (System.IO.StreamWriter file =new System.IO.StreamWriter(FilePath,true))
             {
                    
                    
            `file.Write("SOme Text TO Write" + Environment.NewLine);         
                    
             }
        

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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