使用 StreamWriter 将行附加到文件
我想将行附加到我的文件中。我正在使用 StreamWriter:
StreamWriter file2 = new StreamWriter(@"c:\file.txt");
file2.WriteLine(someString);
file2.Close();
我的文件的输出应该是几个位于彼此下方的字符串,但我只有一行,每次运行此代码时都会被覆盖。
有什么方法可以让 StreamWriter 附加到现有文件吗?
I want to append lines to my file. I am using a 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
将此行: 替换
为以下代码:
然后将您的行写入文本文件,如下所示:
Replace this line:
with this code:
and then write your line to the text file like this:
你可以这样使用
You can use like this
使用此替代:
通过 StreamWriter 构造函数的此重载,您可以选择是附加文件还是覆盖它。
C# 4 及更高版本提供以下语法,有些人认为该语法更具可读性:
Use this instead:
With this overload of the StreamWriter constructor you choose if you append the file, or overwrite it.
C# 4 and above offers the following syntax, which some find more readable:
我假设您每次向文件写入内容时都会执行上述代码的全部。每次打开文件流时,其查找指针都会定位在开头,因此所有写入最终都会覆盖之前的内容。
您可以通过两种方式解决该问题:使用方便的方法
或自己显式重新定位流指针:
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
or by explicitly repositioning the stream pointer yourself:
试试这个:
Try this:
将其替换
为:
true
表示它附加文本。Replace this:
with this:
true
indicates that it appends text.实际上,只有 Jon 的回答(2011 年 9 月 5 日 9:37)与 BaseStream.Seek 对我的案例有效。谢谢乔恩!我需要附加行到 zip 存档的 txt 文件。
Actually only Jon's answer (Sep 5 '11 at 9:37) with BaseStream.Seek worked for my case. Thanks Jon! I needed to append lines to a zip archived txt file.
使用带有第二个参数的此
StreamWriter
构造函数 -真
。Use this
StreamWriter
constructor with 2nd parameter -true
.另一种选择是使用 System.IO.File.AppendText
这相当于其他人给出的 StreamWriter 重载。
另外 File.AppendAllText 可能会提供稍微更简单的界面,而不必担心打开和关闭流。尽管您可能需要担心如何插入自己的换行符。 :)
Another option is using System.IO.File.AppendText
This is equivalent to the StreamWriter overloads others have given.
Also File.AppendAllText may give a slightly easier interface without having to worry about opening and closing the stream. Though you may need to then worry about putting in your own linebreaks. :)
一种更简单的方法是使用 File.AppendText 它将 UTF-8 编码文本附加到现有文件,或者如果指定文件不存在则附加到新文件并返回 System.IO .StreamWriter
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 aSystem.IO.StreamWriter