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. If any such file already exists at the given location, this method opens the file.
See the syntax of the File.CreateText()
method below:
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 objectusing (StreamWriter sw = File.CreateText(path))}}
After executing the above code, the
StreamWriter
class method can be called using thesw
object.