Create a Text File in C#
The following 4 methods can be used to create a text file in C#. In this article and code sample, we will learn how to use these methods to create text files.
File.Create File.CreateText FileInfo.Create FileInfo.CreateText
File.Create Method
The File.Create() method takes a file name with the full path as its first and required parameter and creates a file at the specified location. If same file already exists at the same location, this method overwrites the file.
The following code snippet creates a file Mahesh.txt in C:\Temp folder. If file already exists, the code will delete the existing file. The code writes two arrays of bytes to the file.
The Create method creates and returns a FileStream object that is responsible for reading and writing the specified file.
string fileName = @"C:\Temp\Mahesh.txt";
try
{
// Check if file already exists. If yes, delete it. if (File.Exists(fileName))
{
File.Delete(fileName);
}
// Create a new file using (FileStream fs = File.Create(fileName))
{
// Add some text to file Byte[] title = new UTF8Encoding(true).GetBytes("New Text File"); fs.Write(title, 0, title.Length); byte[] author = new UTF8Encoding(true).GetBytes("Mahesh Chand");
fs.Write(author, 0, author.Length);
}
// Open the stream and read it back. using (StreamReader sr = File.OpenText(fileName))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
catch (Exception Ex)
{
Console.WriteLine(Ex.ToString());
}
What a lovely blog. I’ll certainly be back. Please preserve writing! Maven Sports Illustrated
The guidelines you provided here are rather precious. It had been such a pleasurable surprise to have that waiting for me as i woke up this very day. They are constantly to the point plus easy to learn. Thank you for the clever ideas you have shared right here. Ross Levinsohn
The guidelines you provided here are rather precious. It had been such a pleasurable surprise to have that waiting for me as i woke up this very day. They are constantly to the point plus easy to learn. Thank you for the clever ideas you have shared right here. Ross Levinsohn
I got what you mean ,bookmarked , very nice internet site . Ross Levinsohn Maven
Good story and a pleasant summation of the problem. My only problem with the analysis is given that much of the population joined the chorus of deregulatory mythology, given vested interest is inclined toward perpetuation of the current system and given a lack of a popular cheerleader for your arguments, I’m not seeing much in the way of change. Ross Levinsohn