What is File.CreateText() in C#?
Overview
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.
Syntax
File.CreateText("fileName");
Parameters
fileName: This is the file’s name whose contents we want to overwrite. If the file does not exist, a new one is created.
Return value
A StreamWriter is returned.
Code example
main.cs
test.txt
// 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"));}}
Explanation
- The file
test.txtis created and filled with “Welcome!”. - Line 13: We print out the content of
test.txtbefore overriding it. - Line 16-21: We use the
File.CreateText()method. We overwrite the contents oftest.txt. - Line 24: We print the new contents to the console.