
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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
- Related Questions & Answers
- C# Program to read all the lines of a file at once
- Golang Program to Read the Contents of a File
- How to read the contents of a webpage into a string in java?
- How to read a file into a string in Golang?
- How to read contents of a file using Scanner class?
- Java Program to Create String from Contents of a File
- C Program for copying the contents of one file into another file
- Read whole ASCII file into C++ std::string
- How to read the contents of a JSON file using Java?
- Merge contents of two files into a third file using C
- Print contents of a file in C
- C program to copy the contents of one file to another file?
- What is the best way to read an entire file into a std::string in C++?
- How to read file content into istringstream in C++?
- Write a C program to read a data from file and display
Advertisements