C# add text to text file without rewriting it?

前提是你 提交于 2019-12-13 14:14:18

问题


Let's say I have the following code:

StreamWriter sw = new StreamWriter(File.OpenWrite(Path));
sw.Write("Some stuff here");
sw.Dispose();

This code replaces the contents of the file with "Some stuff here," however I would like to add text to the file rather than replacing the text. How would I do this?


回答1:


You need to tell the StreamWriter you want to append:

var sw = new StreamWriter(path, true);

File.OpenWrite doesn't support appending.




回答2:


You could use the File.AppendAllText method and replace the 3 lines of code you have with:

File.AppendAllText(Path, "blah");

This way you don't have to worry about streams and disposing them (even in the event of an exception which by the way you are not doing properly) and the code is pretty simple and straightforward to the point.




回答3:


Check out System.IO.File.AppendAllText

http://msdn.microsoft.com/en-us/library/ms143356.aspx

You can do what you want doing something like

File.AppendAllText(path, text);



回答4:


There is a StreamWriter constructor which takes a bool as the 2nd parameter, which instructs the writer to append if true.




回答5:


Use the append parameter:

StreamWriter sw = new StreamWriter(Path, true);

http://msdn.microsoft.com/en-us/library/36b035cb.aspx




回答6:


To append text to a file, you can open it using FileMode.Append.

StreamWriter sw = new StreamWriter(File.Open(Path, System.IO.FileMode.Append));

This is just one way to do it. Although, if you don't explicitly need the StreamWriter object, I would recommend using what others have suggested: File.AppendAllText.



来源:https://stackoverflow.com/questions/9559616/c-sharp-add-text-to-text-file-without-rewriting-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!