How to create a text file in C#

The CreateText() method of the File class is used to create a text file in C#. The File.CreateText() method takes a full specified path as a parameter and creates a file at the specified location for writing UTF-8 encoded text. I​f any such file already exists at the given location, this method opens the file.

Syntax

See the syntax of the File.CreateText() method below:

svg viewer

Code

The code snippet below illustrates the process of creating a text file at a specified path using the File.CreateText() method.

using System;
using System.IO;
using System.Text;
class FileCreation
{
public static void Main()
{
string path = @"D:\Text_Files\my_file.txt";
// The line below will create a text file, my_file.txt, in
// the Text_Files folder in D:\ drive.
// The CreateText method that returns a StreamWriter object
using (StreamWriter sw = File.CreateText(path))
}
}

After executing the above code, the StreamWriter class method can be called using the sw object.

Copyright ©2024 Educative, Inc. All rights reserved