Sunday, March 9, 2014

Get StreamReader in .NET

DriveInfo , DirectoryInfo , FileInfo, StreamReader , StreamWriter

What is FileInfo

  • To write / read the content to / write the file, you require file streams.
  • A file stream acts as a pointer for the file, which contains the memory address of the file on the disc.
There are two types of file streams.
1)  Reading Streams
2)  Writing Streams

API:  System.IO.StreamReader (to read the content of the file)

Reading content from the file

Import the API
using System.IO;
Create the stream reader object
StreamReader sr = new StreamReader(file name);
Reade the content
sr.ReadToEnd();
Close the Reader
sr.Close();

Program for StreamReader                                                               

 using System;
using System.IO;
namespace FileReadDemo
{
class Program
{
static void Main(string[] args)
{
string filepath;
Console.WriteLine("Enter the file path:");
filepath = Console.ReadLine();
FileInfo fobj = new FileInfo(filepath);
if (fobj.Exists)
{
StreamReader sr = new StreamReader(filepath);
string content = sr.ReadToEnd();
Console.WriteLine(content);
sr.Close();
}
else
Console.WriteLine("File not found.");
Console.Read();
}
}
}
DriveInfo , DirectoryInfo , FileInfoStreamReader , StreamWriter