I'm using SteamWriter
to write something to a text file, however its overwriting the old data with the new data.
How can I make sure it will just add the new data instead of overwriting the old data?
my code:
class Program
{
const string filename = @"C:\log.txt";
static void Main()
{
FileStream fs;
fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
StreamWriter writer = new StreamWriter(fs);
writer.WriteLine("test");
writer.Close();
fs.Close();
}
}
StreamWriter(String, Boolean) Initializes a new instance of the StreamWriter class for the specified file by using the default encoding and buffer size. If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file.
FileMode parameters control whether a file is overwritten, created, opened, or some combination thereof. Use Open to open an existing file. To append to a file, use Append . To truncate a file or create a file if it doesn't exist, use Create .
Specifically, a FileStream exists to perform reads and writes to the file system. Most streams are pretty low-level in their usage, and deal with data as bytes. A StreamWriter is a wrapper for a Stream that simplifies using that stream to output plain text.
You must call Close to ensure that all data is correctly written out to the underlying stream. Following a call to Close, any operations on the StreamWriter might raise exceptions.
If you use FileMode.Create
, according to MSDN:
Specifies that the operating system should create a new file. If the file already exists, it will be overwritten. This requires FileIOPermissionAccess.Write permission. FileMode.Create is equivalent to requesting that if the file does not exist, use CreateNew; otherwise, use Truncate. If the file already exists but is a hidden file, an UnauthorizedAccessException exception is thrown.
So you need to use FileMode.Append
instead, if you want to add content to the end of the file:
Opens the file if it exists and seeks to the end of the file, or creates a new file. This requires FileIOPermissionAccess.Append permission. FileMode.Append can be used only in conjunction with FileAccess.Write. Trying to seek to a position before the end of the file throws an IOException exception, and any attempt to read fails and throws a NotSupportedException exception.
FileStream fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With