Write string to text file and ensure it always overwrites the existing content.
System.IO.File.WriteAllText (@"D:\path.txt", contents);
- If the file exists, this overwrites it.
- If the file does not exist, this creates it.
- Please make sure you have appropriate privileges to write at the location, otherwise you will get an exception.
Use the File.WriteAllText
method. It creates the file if it doesn't exist and overwrites it if it exists.
Generally, FileMode.Create
is what you're looking for.
Use the file mode enum to change the File.Open
behavior. This works for binary content as well as text.
Since FileMode.Open
and FileMode.OpenOrCreate
load the existing content to the file stream, if you want to replace the file completely you need to first clear the existing content, if any, before writing to the stream. FileMode.Truncate
performs this step automatically
// OriginalFile:
oooooooooooooooooooooooooooooo
// NewFile:
----------------
// Write to file stream with FileMode.Open:
----------------oooooooooooooo
var exists = File.Exists(path);
var fileMode = exists
? FileMode.Truncate // overwrites all of the content of an existing file
: FileMode.CreateNew // creates a new file
using (var destinationStream = File.Open(path, fileMode)
{
await newContentStream.CopyToAsync(destinationStream);
}
FileMode Enum