
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
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 Articles
- C# Program to read all the lines of a file at once
- Golang Program to Read the Contents of a File
- C# Program to Create String from Contents of a File
- How to read the contents of a webpage into a string in java?
- Java Program to Create String from Contents of a File
- Golang program to create string from contents of a file
- How to read a file into a string in Golang?
- How to read contents of a file using Scanner class?
- 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
- What is the best way to read an entire file into a std::string in C++?
- C program to copy the contents of one file to another file?
- Print contents of a file in C

Advertisements