In .NET Framework , the "System.IO.File" class library provides static methods for creating, reading, copying, moving, and deleting files.
Here you can find few sample code snippets to Create,Read and Write a Text file in C#.
Create a Text file and Writing data to it in C#
class TextApp
{
static void Main(string[] args)
{
string fileName = @"F:\Test\Example.txt";
// create a writer and open the file
TextWriter tw = new StreamWriter(fileName);
// write a line of text to the file
tw.WriteLine(DateTime.Now);
// close the stream
tw.Close();
}
}
Read the data from a Textfile in C#
class TextApp
{
static void Main(string[] args)
{
string fileName = @"F:\Test\Example.txt";
// create reader & open file
TextReader tr = new StreamReader(fileName);
// read a line of text
Console.WriteLine(tr.ReadLine());
// close the stream
tr.Close();
}
}
Different ways to write to a file in C# .NET
string fileName = @"F:\Test\Example.txt";
using (FileStream target = File.Open(fileName , FileMode.Append, FileAccess.Write))
{
using (StreamWriter writer = new StreamWriter(target))
{
writer.WriteLine("Hello world");
}
}
string fileName = @"F:\Test\Example.txt";
using (MemoryStream memory = new MemoryStream())
{
using (StreamWriter writer = new StreamWriter(memory))
{
writer.WriteLine("Hello world from memory");
writer.Flush();
using (FileStream fileStream = File.Create(fileName ))
{
memory.WriteTo(fileStream);
}
}
}