The FileInfo.Create method creates a file at the given path. If just a file name is provided without a path, the file will be created in the current folder.
The following code snippet creates a file using the Create method that returns a FileSteam object. The Write method of FileStream can be used to write text to the file.
// Full file name
string fileName = @"C:fileName.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 (FileStream fs = fi.Create())
{
Byte[] txt = new UTF8Encoding(true).GetBytes("New file.");
fs.Write(txt, 0, txt.Length);
Byte[] author = new UTF8Encoding(true).GetBytes("Author CsharpCanBan.Com");
fs.Write(author, 0, author.Length);
}
// 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());
}