Stream Reader Writer Programming Data Structures
Stream Reader Writer Programming Data Structures
Objective Student must understand and learn how to write C# program to access (read/write) text files using StreamReader and StreamWriter of Microsoft Visual Studio .Net Framework.
StreamReader Class
StreamReader Members Read( ) Description
Reads the next character from the input stream Reads a line of characters from the current stream and returns the data as a string Reads the stream from the current position to the end of the stream Checks if it reaches the end of the file Checks if no more characters are available. -1 means no more character.
Syntax / Example using (StreamReader sr = new StreamReader(@"C:\temp\StudFile.txt")) { while (sr.Peek() >= 0) { string liner = sr.ReadLine(); string[] item = liner.Split('#'); Console.WriteLine(item[1]); } } using (StreamReader sr = new StreamReader(@"C:\temp\StudFile.txt")) { while (!sr.EndOfStream) { string liner = sr.ReadLine(); string[] item = liner.Split('#'); Console.WriteLine(item[1]); } }
ReadLine( )
ReadToEnd( )
EndOfStream
Peek()
StreamReader Class
StreamReader Members Dispose( ) Description
Releases the unmanaged resources used by the StreamReader. Closes the current StreamReader
Syntax / Example
string outText; try { StreamReader sr = new StreamReader(@"C:\temp\SampleReceipt.txt"); while ((outText = sr.ReadLine()) != null) { Console.WriteLine(outText); } sr.Close(); sr.Dispose(); Console.WriteLine("\n\n\t\t***********\n\n"); StreamReader sr2 = new StreamReader(@"C:\temp\SampleReceipt.txt"); Console.WriteLine(sr2.ReadToEnd()); sr2.Close(); sr2.Dispose(); } catch (Exception err) { Console.WriteLine(err.Message); }
Close( )
StreamWriter Class
C# uses file streams to deal with stored data. The SreamWriter and StreamReader classes make it easy to write and read data to and from text files in C#. They are classes derived from TextWriter and TextReader classes. Append Mode = true default mode is false Note: include System.IO; (part of directives) StreamWriter Members Write( ) WriteLine( ) NewLine Description
Writes the characters to the stream Writes the characters to the stream, followed by a line terminator (Property) Gets or sets the line terminator string used by the current TextWriter Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream. Closes the current StreamWriter. Automatically flush all buffers to the file. Releases the unmanaged resources used by the SreamWriter
Syntax / Example
try { StreamWriter file = new StreamWriter( @"C:\temp\sisc.txt",true); file.WriteLine(file.NewLine); file.WriteLine(Line Inserted"); file.Write(file.NewLine); file.WriteLine(Another Line He"); file.Flush(); file.Close(); file.Dispose(); Console.WriteLine("Text inserted."); } catch (exception err) { Console.WriteLine(err.message); }
Flush( )
Close( )
Dispose( )
SCREEN OUTPUT