The CreateText()
method of the File class overwrites the contents of an existing file. If the file does not exist, it will be created and filled with the contents.
File.CreateText("fileName");
fileName
: This is the file’s name whose contents we want to overwrite. If the file does not exist, a new one is created.
A StreamWriter
is returned.
// Using System, System.IO,// System.Text and System.Linq namespacesusing System;using System.IO;using System.Text;using System.Linq;class HelloWorld{static void Main(){// Before using the CreateText() methodConsole.WriteLine("Before Overwriting: {0}", File.ReadAllText("test.txt"));// create a new file with contents belowusing(StreamWriter sw = File.CreateText("test.txt")){sw.WriteLine("Welcome");sw.WriteLine("To");sw.WriteLine("Edpresso!");}// check file contentsConsole.WriteLine("After Overwriting: {0}", File.ReadAllText("test.txt"));}}
test.txt
is created and filled with “Welcome!”.test.txt
before overriding it.File.CreateText()
method. We overwrite the contents of test.txt
.