Create a Text File in C# – Programming, Pseudocode Example, C# Programming Example
C# C# Console File

Create a Text File in C#

In this tutorial, i’ll show you How to create a text file in C#.

The following 4 methods can be used to create a text file in C#. In this article and code sample, we will learn how to use these methods to create text files.

  1. File.Create 
  2. File.CreateText 
  3. FileInfo.Create 
  4. FileInfo.CreateText

File.Create Method

The File.Create() method takes a file name with the full path as its first and required parameter and creates a file at the specified location. If same file already exists at the same location, this method overwrites the file.

The following code snippet creates a file test.txt in C:\Temp folder. If file already exists, the code will delete the existing file. The code writes two arrays of bytes to the file.

The Create method creates and returns a FileStream object that is responsible for reading and writing the specified file.

The Create method has four overloaded forms provide options with a file buffer size, file options, and file security.

Create File with Buffer Size

File.Create(name of the file, number of bytes buffered for read and write to the file)

Create File with File Options

The File.Create method takes third parameters as a FileOptions enumeration that can be used to specify advanced options for creating a FileStream object. 

Create File with File Security

The Create method also has an option to specify the file security options. The fourth parameter passed within the Create method of type FileSecurity object.  

File.CreateText Method

The File.CreateText method creates and opens a file for writing UTF-8 encoded text. If file already exists, this method opens the file. 

The following code snippet creates a file using the CreateText method that returns a StreamWriter object. The WriteLine method of SteamLine can be used to add line text to the object and writes to the file. 

FileInfo.Create Method

The FileInfo.Create method creates a file.

The following code snippet creates a file using the Create method that returns a FileSteam object. The Write method of FileStream can be used to write text to the file.

FileInfo.CreateText Method

The FileInfo.CreateText method creates and opens a file for writing UTF-8 encoded text. If file already exists, this method opens the file. 

The following code snippet creates a file using the CreateText method that returns a StreamWriter object. The WriteLine method of SteamLine can be used to add line text to the object and writes to the file. 

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.