Hello:
In this article: You will learn to Write or Read A Text File.
Let's Begin:
First Create a new project (ConsoleApp or WinApp).
And Make sure your program uses these namespaces:
-
using System;
-
using System.IO;
-
using System.Diagnostics;
-
Now, we will begin writing text to a file:
1)- Create a new stream-writer and open the file:
-
TextWriter tw = new StreamWriter(@"C:\Hello.txt");
-
2)- Write text to the file:
3)- Close the file.
4)- Launch the file:
-
Process.Start(@"C:\Hello.txt");
-
Here is all the code:
-
//Creating a new stream-writer and opening the file.
-
TextWriter tsw = new StreamWriter(@"C:\Hello.txt");
-
-
//Writing text to the file.
-
tsw.WriteLine("Hello");
-
-
//Close the file.
-
tsw.Close();
-
-
//Launch the file.
-
Process.Start(@"C:\Hello.txt");
-
-
Console.WriteLine("You're done, press any key to exit...");
-
Console.ReadKey();
-
Now, we will begin reading text from a file:
1)- Creating a new stream-reader and opening the file:
-
TextReader trs = new StreamReader(@"C:\Hello.txt");
-
2)- Reading text of the file:
-
//Reading all the text of the file.
-
Console.WriteLine(trs.ReadToEnd());
-
-
//Or Can Reading a line of the text file.
-
//Console.WriteLine(trs.ReadLine());
-
3)- Close the file:
Here is all the code:
-
//Creating a new stream-reader and opening the file.
-
TextReader trs = new StreamReader(@"C:\Hello.txt");
-
-
//Reading all the text of the file.
-
Console.WriteLine(trs.ReadToEnd());
-
-
//Or Can Reading a line of the text file.
-
//Console.WriteLine(trs.ReadLine());
-
-
//Close the file.
-
trs.Close();
-
-
Console.WriteLine("Press any key to exit...");
-
Console.ReadKey();
-
Hope this helped you.