Read A File Using C#

This program just demonstrates the use of FileStream & StreamReader. The program takes 1 parameter from the user; i.e., the file to read.

  1. using System;  
  2. using System.IO;  
  3. class FileRead {  
  4.     string filereadbuf; // buffer to store the content of file   
  5.     publicvoid ReadFile(string FileName, int FileSize) {  
  6.         char[] buf = newchar[FileSize]; // lets define an array of type char field (i.e. variable) buf   
  7.         // for more help please see .net sdk   
  8.         StreamReader sr = new StreamReader(new FileStream(FileName, FileMode.Open, FileAccess.Read));  
  9.         int retval = sr.ReadBlock(buf, 0, FileSize); // no. of bytes read   
  10.         Console.Write("Total Bytes Read = " + retval + "\n");  
  11.         filereadbuf = newstring(buf); // store it in our field   
  12.         Console.WriteLine(filereadbuf); // lets print on screen   
  13.         sr.Close();  
  14.     }  
  15. }  
  16. class TestFileRead {  
  17.     publicstaticvoid Main(string[] args) {  
  18.         String[] cmdline = Environment.GetCommandLineArgs(); // Get the command line parameter   
  19.         Console.WriteLine("File Reader Using Stream Reader & File Stream \n");  
  20.         if (cmdline.Length < 2) // If no parameter is given will show user the usage   
  21.         {  
  22.             Console.WriteLine("Usage: " + cmdline[0] + " <input file> ");  
  23.             return;  
  24.         }  
  25.         // Using Directory Class & using a Method GetFiles we get file list from the current directory   
  26.         // return value is array of files please see .net sdk documentation for more help.   
  27.         File[] fe = (new Directory(".")).GetFiles(cmdline[1]);  
  28.         if (fe.Length == 0) {  
  29.             Console.WriteLine(cmdline[1] + ": file not found"); // if not found display a message to user   
  30.             return;  
  31.         }  
  32.         FileRead fr = new FileRead();  
  33.         try {  
  34.             fr.ReadFile(cmdline[1], (int) fe[0].Length); // sends 2 parameter filename & length   
  35.         } catch (IOException e) {  
  36.             Console.WriteLine("I/O error occured" + e);  
  37.             return;  
  38.         }  
  39.     } // Close brace of Main   
  40. // close brace of TestFileRead  
I would like to give thanks to Saurabh for his expert help, Mahesh for loading my code on his site (it rocks) and thanks to you too for reading it  -- you know who you are.

If you have any comments or doubts or find something terriblly wrong , please feel free to e-mail me !