How to create a text file in C# ?

By | April 23, 2011

Hi,

How can you create a text file in C# and write to it? Sometimes you may need to create a text file using C sharp program. Here is how you can do that.

using System;
using System.IO;

class MainClass
{
  static void Main(string[] args)
  {
    StreamWriter yourStream= null;
    string yourString= "I Love Coderz Heaven!";

    try
    {
      yourStream = File.CreateText("testFile.txt");
      yourStream.Write(yourString);
    }
    catch (IOException e)
    {
      Console.WriteLine(e);
    }
    catch (Exception e)
    {
      Console.WriteLine(e);
    }
    finally
    {
      if (yourStream!= null)
      {
          yourStream.Close();
      }
    }
  }
}

🙂

4 thoughts on “How to create a text file in C# ?

  1. daigoumee

    Useful blog website, keep me personally through searching it, I am seriously interested to find out another recommendation of it.

    Reply
  2. Maya Adduci

    Beneficial info and excellent design you got here! I want to thank you for sharing your ideas and putting the time into the stuff you publish! Great work!

    Reply
  3. Malik Post author

    @daigoumee -> Glad to see your comment. Thank you so much. We will always try to keep it best.

    Reply
  4. Malik Post author

    @Maya Adduci -> Very glad to hear that comment. Comments like this will always keep us motivated. Thank you sooooo much. 🙂

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *