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 namespaces
using System;
using System.IO;
using System.Text;
using System.Linq;
class HelloWorld
{
static void Main()
{
// Before using the CreateText() method
Console.WriteLine("Before Overwriting: {0}", File.ReadAllText("test.txt"));
// create a new file with contents below
using(StreamWriter sw = File.CreateText("test.txt"))
{
sw.WriteLine("Welcome");
sw.WriteLine("To");
sw.WriteLine("Edpresso!");
}
// check file contents
Console.WriteLine("After Overwriting: {0}", File.ReadAllText("test.txt"));
}
}

Explanation

  • The file test.txt is created and filled with “Welcome!”.
  • Line 13: We print out the content of test.txt before overriding it.
  • Line 16-21: We use the File.CreateText() method. We overwrite the contents of test.txt.
  • Line 24: We print the new contents to the console.

Free Resources