C# Using StreamReader

You want to read a text file using StreamReader from the System.IO namespace in the C# language and base class libraries. With the using statement, which is ideal for this purpose, you can both perform actual file IO and dispose of the system resources.

Tip:StreamReader is an excellent way to read text files.

The using statement allows you to leave the file disposal and opening routines to the C# compiler's knowledge of scope. This statement will be compiled to opcodes that instruct the CLR to do all the error-prone and tedious cleanup work with the file handles in Windows.

 StreamReader [C#]

using System;
using System.IO;

class Program
{
static void Main()
{
// It will free resources on its own.
string line;
using (StreamReader reader = new StreamReader("file.txt"))
{
line = reader.ReadLine();
}
Console.WriteLine(line);
}
}



Note: when objects go out of scope, the garbage collector or finalization code is run and your program's memory is reclaimed. Recall that scope in your C# code is a block between brackets. Scope allows the compiler to make many assumptions about your program.

Read all lines in file It is possible to put an entire file into a collection. One very common requirement for programs is that you need to read in a file line-by-line. You want to store all those lines in a generic List or ArrayList. Here's an example that reads in a file line-by-line and stores it in a List.

Reads all lines [C#]

using System;
using System.Collections.Generic;
using System.IO;

class Program
{
static void Main()
{
// Read in a file line-by-line, and store it all in a List.
List<string> list = new List <string>();
using (StreamReader reader = new StreamReader("file.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
list.Add(line); // Add to list.
Console.WriteLine(line);// Write to console.
}
}
}
}



Overview. It creates a List. In the above code, a new List generic object that stores strings are created. The example shows the using keyword. The using keyword surrounds the StreamReader. This ensures the correct disposal of resources.

Dispose of method This is an error-prone way of using StreamReader, without the using statement. We open a file in one line, deal with the file in another few lines, and then make a call to close the file. The code shown below does this in the C# language but is cumbersome and unclear.

Dispose [C#] StreamReader

using System;
using System.IO;

class Program
{
static void Main()
{
// Read a line from a file the old way.
StreamReader reader = new StreamReader("file.txt");
string line = reader.ReadLine();
reader.Close();

reader.Dispose();
Console.WriteLine(line);
}
}


Popular posts from this blog

How to create zip file to download in JSP- Servlet

How to create DataGrid or GridView in JSP - Servlet

Pinging in ASP.NET Example