DotNET Schools

Blogs & Tutorials for Microsoft.NET and Leading web Technologies

Read and Write a Text File With UTF8 Encoding

Write a Text File with UTF8 Encoding,
  1. public void WriteATxtFileWithUTF8Encoding()  
  2. {  
  3.     string txtFilePath = @"D:\bnarayan.txt";  
  4.     using (StreamWriter writer =  
  5.     new StreamWriter(txtFilePath, true, Encoding.UTF8))  
  6.     {  
  7.         writer.WriteLine("Name: Banketeshvar Narayan");  
  8.         writer.WriteLine("Email Id: bnarayan123@gmail.com");  
  9.     }  
  10. }  
Read Data from Text File With UTF8 Encoding,
  1. public void ReadDataFromTxtFileWithUTF8Encoding(string txtFilePath)  
  2. {  
  3.     if (File.Exists(txtFilePath))  
  4.     {  
  5.         using(var reader = new StreamReader(File.OpenRead(txtFilePath), Encoding.UTF8))  
  6.         {  
  7.             while (!reader.EndOfStream)  
  8.             {  
  9.                 var line = reader.ReadLine();  
  10.                 if (!String.IsNullOrEmpty(line))  
  11.                 {  
  12.                     Console.WriteLine(line);  
  13.                 }  
  14.             }  
  15.         }  
  16.     }  
  17. }  
Calling Read and Write methods for Text Files
  1. static void Main(string[] args)  
  2. {  
  3.     Program p = new Program();  
  4.     p.WriteATxtFileWithUTF8Encoding();  
  5.     p.ReadDataFromTxtFileWithUTF8Encoding(@"D:\bnarayan.txt");  
  6. }