- 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
C# Program to read contents of a file into a string at once
Use ReadToEnd() method to read the contents of a file in a string.
Set it under StreamReader and read the file −
using (StreamReader sr = new StreamReader("new.txt")){ string res = sr.ReadToEnd(); Console.WriteLine(res); }
The following is the complete code −
Example
using System.IO; using System; public class Demo { public static void Main() { using (StreamWriter sw = new StreamWriter("new.txt")) { sw.WriteLine("One"); sw.WriteLine("Two"); } using (StreamReader sr = new StreamReader("new.txt")) { string res = sr.ReadToEnd(); Console.WriteLine(res); } } }
It creates the file “new.text” and adds text to it. After that, using StreamReader class and ReadToEnd() method, it reads the contents of the file into a string −
Output
The following is the output.
One Two
Advertisements