Write To File in C#

by Shabbir on April 29, 2008

in C#

Today we will create a console application written in C# for writing to files.
We will use the StreamWriter class that is implemented in .Net Framework.

Create new C# project (Ctrl+Shift+N), and choose Console Application from the Templates menu on the right.
The editor will create the main code

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace WriteToFile
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12.  
  13. }
  14. }
  15. }

Below the using System.Text; add this code

  1. using System.IO;

That is the namespace where the StreamWriter class is declared in.

Now, in the Main function add the folowing code

  1. StreamWriter sw = new StreamWriter("text.txt");
  2. sw.WriteLine(DateTime.Now + " : The program is executed");
  3. sw.Write("Code");
  4. sw.Write("It");
  5. sw.WriteLine("Well.com");
  6. sw.Close();

As you see, in the above code we are creating an object from the StreamWriter class, and we tell the object to write in the file "text.txt" (if the file doesn't exist, it will be created). So we are writing some text in the file using the WriteLine() and Write() functions. It's used and the DateTime class, so in the text file will be written the time where the file was changed.
Very important is, when we finish with writing, we must close the file with sw.Close(). If the file isn't closed, we are leaving an opened handle, so other programms can't access that file.

This will be written to file

29.04.2008 13:00:22 : The program is executed
www.codeitwell.com

Every time we execute the program, the file will be erased, and then written again.
If you don't want this, make this changes in the creating the StreamWriter object sw

  1. StreamWriter sw = new StreamWriter("text.txt", true);

Sharing is Caring...

Leave a Comment

{ 1 trackback }

Previous post:

Next post:

    About the Author

  • author photo

    My Name is Shabbir Bhimani and I am developer by profession in the field of applications, web and database. Currently doing full time online marketing and like to share my experiences on how you can make money online @ CodeItWell.com. Read more ...


    See how you can get in touch with me.