- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to open a plain text file in C#?
To open a plain text file, use the StreamReader class. The following opens a file for reading −
StreamReader sr = new StreamReader("d:/new.txt")
Now, display the content of the file −
while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); }
Here is the code −
Example
using System; using System.IO; namespace FileApplication { class Program { static void Main(string[] args) { try { using (StreamReader sr = new StreamReader("d:/new.txt")) { string line; // Read and display lines from the file until // the end of the file is reached. while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } } } catch (Exception e) { // Let the user know what went wrong. Console.WriteLine("The file could not be read:"); Console.WriteLine(e.Message); } Console.ReadKey(); } } }
Output
The file could not be read: Could not find a part of the path "/home/cg/root/4281363/d:/new.txt".
Advertisements