Reader Level:
ARTICLE

Create a Text File in C#

Posted by Mahesh Chand Articles | Files, Directory, IO June 08, 2012
This article demonstrates different ways to create a text file in C#.
  • 0
  • 0
  • 124083

Create a Text File in C# 

The File class in the .NET Framework class library provides static methods for creating, reading, copying, moving, and deleting files. In this article, we will see how to create a text file using different options available in .NET. 

We can create a file in four different following methods
  • File.Create 
  • File.CreateText 
  • FileInfo.Create 
  • 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 Mahesh.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. 

string fileName = @"C:\Temp\Mahesh.txt";

try
{
    // Check if file already exists. If yes, delete it. 
    if (File.Exists(fileName))
    {
        File.Delete(fileName);
    }

    // Create a new file 
    using (FileStream fs = File.Create(fileName)) 
    {
        // Add some text to file
        Byte[] title = new UTF8Encoding(true).GetBytes("New Text File");
        fs.Write(title, 0, title.Length);
        byte[] author = new UTF8Encoding(true).GetBytes("Mahesh Chand");
        fs.Write(author, 0, author.Length);
    }

    // Open the stream and read it back.
    using (StreamReader sr = File.OpenText(fileName))
    {
        string s = "";
        while ((s = sr.ReadLine()) != null)
        {
            Console.WriteLine(s);
        }
    }
}
catch (Exception Ex)
{
    Console.WriteLine(Ex.ToString());
}  
 
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)

FileStream fs = File.Create(fileName, 1024);

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. 

FileStream fs = File.Create(fileName, 1024, FileOptions.WriteThrough);

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.  

try
{
    string fileName = @"C:\Temp\Mahesh2.txt";
    // Create File Security 
    FileSecurity fSecurity = new FileSecurity(); 
    fSecurity.AddAccessRule(new FileSystemAccessRule(@"DomainName\AccountName", FileSystemRights.ReadData, AccessControlType.Allow));

    using (FileStream fs = File.Create(fileName, 1024, FileOptions.WriteThrough, fSecurity))
    {
        // Add some text to file
        Byte[] title = new UTF8Encoding(true).GetBytes("New Text File");
        fs.Write(title, 0, title.Length);
        byte[] author = new UTF8Encoding(true).GetBytes("Mahesh Chand");
        fs.Write(author, 0, author.Length);
    }
    Console.WriteLine("Adding access control entry for " + fileName);   
    Console.WriteLine("Done.");
}
catch (Exception e)
{
    Console.WriteLine(e);
}

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. 


string fileName = @"C:\Temp\MaheshTX.txt";

try
{
    // Check if file already exists. If yes, delete it. 
    if (File.Exists(fileName))
    {
        File.Delete(fileName);
    }

    // Create a new file 
    using (StreamWriter sw = File.CreateText(fileName))
    {
        sw.WriteLine("New file created: {0}", DateTime.Now.ToString());
        sw.WriteLine("Author: Mahesh Chand");
        sw.WriteLine("Add one more line ");
        sw.WriteLine("Add one more line ");
        sw.WriteLine("Done! ");
    }

    // Write file contents on console. 
    using (StreamReader sr = File.OpenText(fileName))
    {
        string s = "";
        while ((s = sr.ReadLine()) != null)
        {
            Console.WriteLine(s);
        }
    }
}
catch (Exception Ex)
{
    Console.WriteLine(Ex.ToString());
}


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. 

string fileName = @"C:\Temp\MaheshTXFI.txt";
FileInfo fi = new FileInfo(fileName);

try
{
    // Check if file already exists. If yes, delete it. 
    if (fi.Exists)
    {
        fi.Delete();
    }

    // Create a new file 
    using (FileStream fs = fi.Create())
    {
        Byte[] txt = new UTF8Encoding(true).GetBytes("New file.");
        fs.Write(txt, 0, txt.Length);
        Byte[] author = new UTF8Encoding(true).GetBytes("Author Mahesh Chand");
        fs.Write(author, 0, author.Length);
    }

    // Write file contents on console. 
    using (StreamReader sr = File.OpenText(fileName))
    {
        string s = "";
        while ((s = sr.ReadLine()) != null)
        {
            Console.WriteLine(s);
        }
    }
}
catch (Exception Ex)
{
    Console.WriteLine(Ex.ToString());
}


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. 


string fileName = @"C:\Temp\MaheshTXFITx.txt";
FileInfo fi = new FileInfo(fileName);

try
{
    // Check if file already exists. If yes, delete it. 
    if (fi.Exists)
    {
        fi.Delete();
    }

    // Create a new file 
    using (StreamWriter sw = fi.CreateText())
    {
        sw.WriteLine("New file created: {0}", DateTime.Now.ToString());
        sw.WriteLine("Author: Mahesh Chand");
        sw.WriteLine("Add one more line ");
        sw.WriteLine("Add one more line ");
        sw.WriteLine("Done! ");
    }

    // Write file contents on console. 
    using (StreamReader sr = File.OpenText(fileName))
    {
        string s = "";
        while ((s = sr.ReadLine()) != null)
        {
            Console.WriteLine(s);
        }
    }
}
catch (Exception Ex)
{
    Console.WriteLine(Ex.ToString());
}


Summary

In this article, I demonstrated several ways to create a file in C#.

Further Readings 

Here is a list of more articles and tutorials on files and directories: 





COMMENT USING

Trending up