Write string to text file and ensure it always overwrites the existing content.

C#FileText

C# Problem Overview


I have a string with a C# program that I want to write to a file and always overwrite the existing content. If the file isn't there, the program should create a new file instead of throwing an exception.

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

Use the File.WriteAllText method. It creates the file if it doesn't exist and overwrites it if it exists.

Solution 3 - C#

Generally, FileMode.Create is what you're looking for.

Solution 4 - C#

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

Solution 5 - C#

If your code doesn't require the file to be truncated first, you can use the FileMode.OpenOrCreate to open the filestream, which will create the file if it doesn't exist or open it if it does. You can use the stream to point at the front and start overwriting the existing file?

I'm assuming your using a streams here, there are other ways to write a file.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionleoraView Question on Stackoverflow
Solution 1 - C#HemantView Answer on Stackoverflow
Solution 2 - C#GuffaView Answer on Stackoverflow
Solution 3 - C#Thomas DaneckerView Answer on Stackoverflow
Solution 4 - C#J ScottView Answer on Stackoverflow
Solution 5 - C#SpenceView Answer on Stackoverflow