File.CreateText Method in C#

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.

// Full file name

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());

}

Up Next
    Ebook Download
    View all
    Learn
    View all