There are 4 possible methods available to create a new text file using C# and in this article, I have example of creating text file in C# using all 4 methods one by one.

Here are the 4 possible methods available in C# to create text file

  1. File.Create: Creates or overwrites a file in the specified path, write using FileStream
  2. File.CreateText: Creates or opens a file for writing UTF-8 encoded text. If the file already exists, its contents are overwritten, uses Streamwriter to write content on file.
  3. FileInfo.Create: Creates a file, using FileInfo Reference and write using FileStream
  4. FileInfo.CreateText: Again it uses FileInfo Reference to create text file and then Creates a StreamWriter that writes a new text file.

Using File.Create

While using File.Create method in C#, we pass a string file path where text file will be created and then using StreamWriter, we can write text to file.

Here is the example:

using System;
using System.IO;
using System.Text;

namespace CreateTextFile
{
    public class Program
    {
        static void Main(string[] args)
        {
            //file location
            string path = @"D:\SampleTextFile.txt";

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

                // Create the file, or overwrite if the file exists.
                using (FileStream fs = File.Create(path))
                {
                    byte[] info = new UTF8Encoding(true).GetBytes("Something to write on text file.");
                    // Add some information to the file.
                    fs.Write(info, 0, info.Length);

                    //\n is used to break line and add text to new line
                    byte[] someMoreDetails = new UTF8Encoding(true).GetBytes("\nMore text on file.");
                    fs.Write(someMoreDetails, 0, someMoreDetails.Length);
                }

                // Open the stream and read it back.
                using (StreamReader sr = File.OpenText(path))
                {
                    string s = "";
                    while ((s = sr.ReadLine()) != null)
                    {
                        //print contents
                        Console.WriteLine(s);
                    }
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    }
}

Output:

Something to write on text file.
More text on file.

C#-create-text-file

In the above code, we are creating a text file 'SampleTextFile.txt' in hard disk location, D:\SampleTextFile.txt. 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.

Using File.CreateText

This method is similar to above one, difference is that it return StreamWriter instead of FileStream.

Using That Stream, we write content to file easily as shown below in C#.

using System;
using System.IO;
using System.Text;

namespace CreateTextFile
{
    public class Program
    {
        static void Main(string[] args)
        {
            //file location
            string path = @"D:\SampleTextFile.txt";

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

                // Create the file, or overwrite if the file exists.
                using (StreamWriter sw = File.CreateText(path))
                {
                    sw.WriteLine("Hello World");
                    sw.WriteLine("This is Some Text");
                    sw.WriteLine("Welcome");
                }

                // Open the stream and read it back.
                using (StreamReader sr = File.OpenText(path))
                {
                    string s = "";
                    while ((s = sr.ReadLine()) != null)
                    {
                        //print contents
                        Console.WriteLine(s);
                    }
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    }
}

Output:

Hello World
This is Some Text
Welcome

In this methods, if the file specified by path does not exist, it is created.

If the file does exist, its contents are overwritten. Additional threads are permitted to read the file while it is open.

Using FileInfo.Create

In this method, we will have to create file reference first, then using that reference we call .Create() method and write text using FileStream returned.

Here is the complete C# code

using System;
using System.IO;
using System.Text;

namespace CreateTextFile
{
    public class Program
    {
        static void Main(string[] args)
        {
            //file location
            string path = @"D:\SampleTextFile.txt";

            // Create a reference to a file.
            FileInfo fi = new FileInfo(path);

            // Delete the file if it exists.
            if (fi.Exists)
            {
                fi.Delete();
            }

            try
            {

                //actually Create the file using above reference
                using (FileStream fs = fi.Create())
                {
                    Byte[] info = new UTF8Encoding(true).GetBytes("Sample text to add here.");

                    //Add some information to the file.
                    fs.Write(info, 0, info.Length);
                }

                // Open the stream and read it back.
                using (StreamReader sr = File.OpenText(path))
                {
                    string s = "";
                    while ((s = sr.ReadLine()) != null)
                    {
                        //print contents
                        Console.WriteLine(s);
                    }
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    }
}

Output:

Sample text to add here.

Using FileInfo.CreateText

In this one again need to create File Reference first using that, we create file which returns StreamWriter and using that we write text on File in C#.

Here is code sample

using System;
using System.IO;
using System.Text;

namespace CreateTextFile
{
    public class Program
    {
        static void Main(string[] args)
        {
            //file location
            string path = @"D:\SampleTextFile.txt";
            //create reference to file
            FileInfo fi = new FileInfo(path);

            // Delete the file if it exists.
            if (fi.Exists)
            {
                fi.Delete();
            }

            try
            {

                //Create a file to write to.
                using (StreamWriter sw = fi.CreateText())
                {
                    sw.WriteLine("Hello World");
                    sw.WriteLine("Again and");
                    sw.WriteLine("Welcome");
                }

                // Open the stream and read it back.
                using (StreamReader sr = File.OpenText(path))
                {
                    string s = "";
                    while ((s = sr.ReadLine()) != null)
                    {
                        //print contents
                        Console.WriteLine(s);
                    }
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    }
}

Output:

Hello World
Again and
Welcome

That's it.

You may also like to read:

Read file in C# (Text file .NET and .NET Core example)

How to get file extension or file size in C# ? ( Code With Example )

File I/O in C# (Read, Write, Delete, Copy file using C#)

Remove last character from string in C#

SingleOrDefault vs FirstOrDefault in C#

How to read pdf file in C#? (Working example using iTextSharp)

Extract Text from image in C# using Tesseract

Understanding Enums in C# & it's advantages with example

How to create .pfx file from certificate and private key