C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Using: This statement will be compiled to instructions that tell the runtime to do all the cleanup works on the Windows file handles.
UsingInfo: A scope is a block between brackets. When objects go out of scope, the garbage collector or finalization code is run.
Thus: Scope allows the compiler to make many assumptions about your program. It can tell where the object becomes unreachable.
C# program that uses StreamReader
using System;
using System.IO;
class Program
{
static void Main()
{
// ... The StreamReader will free resources on its own.
string line;
using (StreamReader reader = new StreamReader("file.txt"))
{
line = reader.ReadLine();
}
Console.WriteLine(line);
}
}
Output
First line of your file.txt file.
C# program that uses while-true loop
using System;
using System.IO;
class Program
{
static void Main()
{
using (StreamReader reader = new StreamReader("C:\\programs\\file.txt"))
{
while (true)
{
string line = reader.ReadLine();
if (line == null)
{
break;
}
Console.WriteLine(line); // Use line.
}
}
}
}
Output
123
Bird
Hello friend
New: The program creates a List. This List generic collection can store strings.
While: It runs a while-loop. This loop reads in lines until the end of the file.
And: ReadLine returns null at the end of a file. There is no need to check for EOF. Finally it adds lines to the List.
WhileC# program that reads all lines
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.
}
}
}
}
Output
First line of your file.txt file.
Second line.
Third line.
Last line.
Warning: There are problems with this style of code. It is harder to type and read, and bugs could creep into the code.
However: Other than those problems, it works well. If the file is not there, it will throw an exception.
Exception: If the exception is thrown, you must have a finally block to release the unmanaged resources.
FinallyC# program that uses Dispose
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();
// ... We should call Dispose on "reader" here, too.
reader.Dispose();
Console.WriteLine(line);
}
}
Output
First line of file.txt file.
Async: For situations where you have excess CPU usage during file loads, try using the Async method for a speedup. A benchmark is provided.
StreamReader ReadToEndAsync