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;
Now, in the Main function add the folowing code:
StreamWriter sw = new StreamWriter("file.txt");
sw.WriteLine("Hello!");
sw.Write("CodingThis");
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 “file.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:
Hello!
CodingThis
Related Research:
Visit us for more Programming and Technology Research.











