问题
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