File Handling in C#:
We can read or Write data on a text file Using C#. It is also called Filing in Computer Programming. We use System.IO namespace to Handle Files in C#. IO
namespace includes classes that facilitate reading and writing of data to data
streams and files.
Now Coming directly to the point, I use TextWriter Class usually to Read or Write Data on text Files. Following are the Steps to Read or Write Data on Text Files in C#:
For Writing Data on Text File:
TextWriter tw; // Using Class TextWriter , Text file will be in debug folder of Program,
using (tw = new StreamWriter(@"new.txt", true)) // We write using because we donot want to make a text file when we run a program and delete the existing data.. so this will use the previous file, and make a new file of dooesn't exist as we use "true"
{
Console.WriteLine("Enter data to Store");
string Data = Console.ReadLine(); // Reading data from Console Screen
tw.WriteLine(Data); // Writing data on text file
tw.Close(); // to close the file
}
For Reading Data From Text file:
TextReader tr = new StreamReader(@"new.txt"); //using TextWriter Class, Text file is in debug folder of Program,
string data = tr.ReadToEnd(); // Reading data from text file
Console.WriteLine(data);
tr.Close(); // to close the file
Output:
Thanks for reading, Like this if you understood. It helps a lot to keep us motivated
0 comments:
Post a Comment