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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace WriteToFile
- class Program
- static void Main(string args)
Below the using System.Text; add this code
- using System.IO;
That is the namespace where the StreamWriter class is declared in.
Now, in the Main function add the folowing code
- StreamWriter sw = new StreamWriter("text.txt");
- sw.WriteLine(DateTime.Now + " : The program is executed");
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
- StreamWriter sw = new StreamWriter("text.txt", true);