Tuesday, May 13, 2008

Code in C# to Display a text file

/*
C#: The Complete Reference
by Herbert Schildt

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/

/* Display a text file.

To use this program, specify the name
of the file that you want to see.
For example, to see a file called TEST.CS,
use the following command line.

ShowFile TEST.CS
*/

using System;
using System.IO;

public class ShowFile {
public static void Main(string[] args) {
int i;
FileStream fin;

try {
fin = new FileStream(args[0], FileMode.Open);
}
catch(FileNotFoundException exc) {
Console.WriteLine(exc.Message);
return;
}
catch(IndexOutOfRangeException exc) {
Console.WriteLine(exc.Message + "\nUsage: ShowFile File");
return;
}

// read bytes until EOF is encountered
do {
try {
i = fin.ReadByte();
}
catch(Exception exc) {
Console.WriteLine(exc.Message);
return;
}
if(i != -1)
Console.Write((char) i);
} while(i != -1);

fin.Close();
}
}

0 comments: