Minifycode 2022-04-26 Viewed 1.5K times C#

In this article, you will learn how to use StreamReader method in c#


C# StreamReader class is used to read string from the stream. It inherits TextReader class. It provides Read(), ReadLine(),
ReadBlock() and ReadToEnd() methods to read data from the stream.

C# StreamReader example to read one line


See the simple example of StreamReader class that reads a single line of data from the file.

using System;  
using System.IO;  
public class StreamReaderExample  
{  
    public static void Main(string[] args)  
    {  
        FileStream f = new FileStream("f:\\txt.txt", FileMode.OpenOrCreate);  
        StreamReader s = new StreamReader(f);  
  
        string line=s.ReadLine();  
        Console.WriteLine(line);  
  
        s.Close();  
        f.Close();  
    }  
}  


Output:

Hello

 
C# StreamReader example to read all lines

 

using System;  
using System.IO;  
public class StreamReaderExample  
{  
    public static void Main(string[] args)  
    {  
        FileStream f = new FileStream("f:\\txt.txt", FileMode.OpenOrCreate);  
        StreamReader s = new StreamReader(f);  
  
        string line = "";  
        while ((line = s.ReadLine()) != null)  
        {  
            Console.WriteLine(line);  
        }  
        s.Close();  
        f.Close();  
    }  
}  

Output:

 

Hello
this is file


C# StreamReader read web page


In the following example, we read HTML data from a web page.

using var httpClient = new HttpClient();
var url = "https://www.minifycode.in";

var stream = await httpClient.GetStreamAsync(url);

using var sr = new StreamReader(stream);

string content = sr.ReadToEnd();
Console.WriteLine(content);

C# StreamReader ReadLine


The ReadLine method reads a line of characters from the current stream and returns the data as a string. It returns null if the end of the input stream is reached.

var fileName = "txt.txt";

using var sr = new StreamReader(fileName);

string? line;

while ((line = sr.ReadLine()) != null)
{
    Console.WriteLine(line);
}


C# StreamReader ReadBlock


The ReadBlock method reads the specified maximum number of characters from the current stream and writes the data to a buffer, beginning at the specified index. It returns the number of characters that have been read.

var fileName = "txt.txt";

using var sr = new StreamReader(fileName);

char[] buf = new char[25];

int n = sr.ReadBlock(buf, 0, buf.Length);

Console.WriteLine($"{n} character reads");
Console.WriteLine(buf);


C# StreamReader ReadToEnd


The ReadToEnd method reads all characters from the current position to the end of the stream. It returns the rest of the stream as a string, from the current position to the end; if the current position is at the end of the stream, it returns an empty string.

var fileName = "txt.txt";
using var sr = new StreamReader(fileName);
string content = sr.ReadToEnd();
Console.WriteLine(content);


StreamReader.Peak() method

Stream.Reader.Peek() method checks if there are more characters are left to read in a file. The method returns an integer. If the value is less than 0, there are no more characters left to read. The following code snippet uses the Peak() method to check if there are more characters left to read in a file.
 

using (StreamReader reader = new StreamReader(new FileStream(fileName, FileMode.Open)))  
{  
while (reader.Peek() >= 0)  
{  
// Your code here  
}  
}  

 

asynchronously()


The following example instantiates a StreamReader object and calls its ReadAsync method to read a file asynchronously.

using System;
using System.IO;
using System.Threading.Tasks;

class Example
{
    static async Task Main()
    {
        await ReadAndDisplayFilesAsync();
    }

    static async Task ReadAndDisplayFilesAsync()
    {
        String filename = "txt.txt";
        Char[] buffer;

        using (var sr = new StreamReader(filename)) {
            buffer = new Char[(int)sr.BaseStream.Length];
            await sr.ReadAsync(buffer, 0, (int)sr.BaseStream.Length);
        }

        Console.WriteLine(new String(buffer));
    }
}

 

ReadToEndAsync()

Reads all characters from the current position to the end of the stream asynchronously and returns them as one string.

using System;
using System.IO;

namespace ConsoleApplication
{
    class Program
    {
        static async Task Main()
        {
            await ReadCharacters();
        }

        static async Task ReadCharacters()
        {
            String result="";
            using (StreamReader reader = File.OpenText("txt.txt"))
            {
                Console.WriteLine("Opened file.");
                result = await reader.ReadToEndAsync();
                Console.WriteLine("Show Result: " + result);
            }
        }
    }
}

C# StreamReader class is used to read string from the stream. It inherits TextReader class. It provides Read(), ReadLine(), ReadBlock() and ReadToEnd()
C# is a programming language developed by Microsoft that runs on the .NET Framework. C# is used to develop web, desktop, mobile, games and much more application. C# is a object-oriented programming language developed by Microsoft within its .NET Framework. Led by Anders Hejlsberg, your basic C# programming and will also take you through various advanced concepts related to C# programming language. C# such as control statements, objects and classes, inheritance, constructor, destructor, this, static, sealed, polymorphism, abstraction, abstract class, interface, File IO, Collections, namespace, encapsulation, properties, indexer, arrays, strings, regex, exception handling, multithreading etc. For example... using System; namespace MinifyCode { class Program { static void Main(string[] args) { Console.WriteLine("Hello Minify Code"); } } } Output: Hello Minify Code In this article you will learn, what is server side controls. We will discuss each of these objects in due time. In this tutorial we will explore the Server object, the Request object, and the Response object. Session Application Cache Request Response Server User Trace Server Object The Server object in Asp.NET is an instance of the System.Web.HttpServerUtility class. The HttpServerUtility class provides numerous properties and methods to perform many type of jobs. Methods and Properties of the Server object The methods and properties of the HttpServerUtility class are exposed through the intrinsic Server object provided by ASP.NET. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Optimization; using System.Web.Routing; using System.Web.Security; using System.Web.SessionState; using System.Data.Entity; namespace minifycode { public class Global : HttpApplication { void Application_Start(object sender, EventArgs e) { // Code that runs on application startup RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // Initialize the product database. Database.SetInitializer(new ProductDatabaseInitializer()); // Create custom role and user. RoleActions roleActions = new RoleActions(); roleActions.AddUserAndRole(); // Add Routes. RegisterCustomRoutes(RouteTable.Routes); } void RegisterCustomRoutes(RouteCollection routes) { routes.MapPageRoute( "ProductsCategoryRoute", "Category/{categoryName}", "~/ProductList.aspx" ); routes.MapPageRoute( "ProductNameRoute", "Product/{productName}", "~/ProductDetails.aspx" ); } } }