TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# StreamReader ReadToEnd Example (Read Entire File)

Use the ReadToEnd method on the StreamReader to read an entire text file into a string.
StreamReader, ReadToEnd. Sometimes we want to read in a file line-by-line, but other times we just want the entire file at once. The ReadToEnd method on StreamReader is helpful here.StreamReader
With this method, we consume the entire file into a string in one line. This is similar in operation to File.ReadAllText. But StreamReader requires some surrounding code.File.ReadAllText
An example. Here is the ReadToEnd method. We can call it inside a using-statement for best effect. Please change the file path before you run this program on your system.
C# program that uses StreamReader ReadToEnd using System; using System.IO; class Program { static void Main() { using (StreamReader reader = new StreamReader(@"C:\programs\file.txt")) { // Read entire text file with ReadToEnd. string contents = reader.ReadToEnd(); Console.WriteLine(contents); } } } Output Thank you Friend
A review. Which methods are best? If you already have a StreamReader, then using ReadToEnd is probably the best solution to read an entire text file into a string.

However: In other programs, where no StreamReader object exists, File.ReadAllText is probably a clearer method to use.

ReadToEndAsync. With ReadToEndAsync on StreamReader, we can achieve a significant performance boost. But this only helps when a lot of CPU usage is present during processing.StreamReader ReadToEndAsync
A summary. ReadToEnd is important enough that it deserves special attention. I have used it recently in a program—sometimes it leads to clearer code than ReadLine and while-loops would.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf