Mega Code Archive

 
Categories / C# / File Stream
 

Uses methods in the File class to check whether a file exists

/* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794 */ // Exists.cs -- Uses methods in the File class to dheck whether a file exists. //              If it exists, it then opens and reads the file to the console. // //              Compile this program with the following command line //                  C:>csc Exists.cs using System; using System.IO; namespace nsStreams {     public class Exists     {         static public void Main (string [] args)         {             if (args.Length == 0)             {                 Console.WriteLine ("Please enter a file name");                 return;             }             if (!File.Exists (args[0]))             {                 Console.WriteLine (args[0] + " does not exist");                 return;             }             StreamReader reader;             try             {                 reader = File.OpenText (args[0]);             }             catch (Exception e)             {                 Console.WriteLine (e.Message);                 Console.WriteLine ("Cannot open " + args[0]);                 return;             }             while (reader.Peek() >= 0)             {                 Console.WriteLine (reader.ReadLine ());             }             reader.Close ();         }     } }