C# Simple Ways to Create, Open, Write and Read text file
Updated on: March 20, 2023
Using C# we can easily create any text file, Write new text or Append new text to the end of the file and we can read the content of the text file in C Sharp using below line of code:
using System;
using System.IO;
namespace FileOperationsSolution
{
internal class Program
{
static void Main(string[] args)
{
string testFilePath = "C:/test.txt";
//Creating a new text file if not exists, then open it to append text in write mode
using (FileStream fs = new FileStream(testFilePath, FileMode.Append,FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(fs))
{
string content = "New Content Added at: " + DateTime.Now;
sw.WriteLine(content);
}
}
//Read the entire content of text file and print to Console
string fileData= File.ReadAllText(testFilePath);
Console.WriteLine(fileData);
Console.ReadLine();
}
}
}
Here, in above example, FileMode.Append will create a new file if it doesn't exists, so we don't have to specifically write code like if(!File.Exists(testFilePath )){File.Create(testFilePath);}
Also, we have used StreamWriter() to write string content to the file using WriteLine() method.
After file is created and after we have opened it in Write Mode to Append text, then we can read the content of the file using File.ReadAllText(testFilePath)