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

leora picture leora · Aug 4, 2009 · Viewed 224.8k times · Source

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.

Answer

Hemant picture Hemant · Aug 4, 2009
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.