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:
Expand|Select|Wrap|Line Numbers
- using System;
- using System.IO;
- using System.Diagnostics;
1)- Create a new stream-writer and open the file:
Expand|Select|Wrap|Line Numbers
- TextWriter tw = new StreamWriter(@"C:\Hello.txt");
Expand|Select|Wrap|Line Numbers
- tw.WriteLine("Hello");
Expand|Select|Wrap|Line Numbers
- tw.Close();
Expand|Select|Wrap|Line Numbers
- Process.Start(@"C:\Hello.txt");
Expand|Select|Wrap|Line Numbers
- //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:
Expand|Select|Wrap|Line Numbers
- TextReader trs = new StreamReader(@"C:\Hello.txt");
Expand|Select|Wrap|Line Numbers
- //Reading all the text of the file.
- Console.WriteLine(trs.ReadToEnd());
- //Or Can Reading a line of the text file.
- //Console.WriteLine(trs.ReadLine());
Expand|Select|Wrap|Line Numbers
- trs.Close();
Expand|Select|Wrap|Line Numbers
- //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();