StreamReader

You use a StreamReader object to read from a text file.
There are a number of ways you can obtain the StreamReader object
The fifth line, lets the system decide the best type of encoding

System.IO.StreamReader oStreamReader; 
oStreamReader = new System.IO.StreamReader(@"C:\\Temp\\textfile.txt");
oStreamReader = new System.IO.StreamReader(@"C:\\Temp\\textfile.txt", System.Text.Encoding.ASCII);
oStreamReader = new System.IO.StreamReader(@"C:\\Temp\\textfile.txt", System.Text.Encoding.Unicode);
oStreamReader = new System.IO.StreamReader(@"C:\\Temp\\textfile.txt", true);

Using a FileStream

System.IO.StreamReader oStreamReader; 
System.IO.FileStream oFileStream;
oFileStream = new System.IO.FileStream(@"C:\\Temp\\textfile.txt", FileMode.Open);
oStreamReader = new System.IO.StreamReader(objFileStream);

Using a Stream
This lets you specify the mode, access and share

System.IO.StreamReader oStreamReader; 
System.IO.Stream oStream;
oStream = System.IO.File.Open(@"C:\\Temp\\textfile.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
oStreamReader = new System.IO.StreamReader(oStream, System.Text.Encoding.UTF8);

Using a FileInfo

System.IO.StreamReader oStreamReader; 
System.IO.FileInfo oFileInfo;
oFileInfo = new System.IO.FileInfo(@"C:\\Temp\\textfile.txt");
oStreamReader = objFileInfo.OpenText

Using File.OpenText

System.IO.StreamReader oStreamReader; 
oStreamReader = System.IO.File.OpenText(@"C:\\Temp\\textfile.txt");


Reading the Contents

There are several ways to read from a StreamReader


ReadToEndAsyn

This can also be used to read all the remaining characters.

string sWholeFile; 

// async
using (oStreamReader)
{
   sWholeFile = await oStreamReader.ReadToEndAsync();
}
// sync
sWholeFile = objStreamReader.ReadToEnd;

ReadToEnd



ReadLine

string sLine; 
string s = String.Empty;

while( (s = oStreamReader.ReadLine() ) != null);
{
}


Read

Read a Single Character

string sCharacter; 
sCharacter = objStreamReader.Read;


Peek

The Peek method actually returns the code of the next character in the stream without actually extracting it, or it returns -1 if there are no more characters.
This method is used to test for the end of the file.

while (oStreamReader.Peek = -1) 
{
read the stream
}

© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext