The FileInfo.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:TempMaheshTXFITx.txt";
FileInfo fi = new FileInfo(fileName);
try
{
// Check if file already exists. If yes, delete it.
if (fi.Exists)
{
fi.Delete();
}
// Create a new file
using (StreamWriter sw = fi.CreateText())
{
sw.WriteLine("New file created: {0}", DateTime.Now.ToString());
sw.WriteLine("Author: CsharpCanBan.Com");
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());
}