Check if a file exists, open and read the file

 
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
 
 
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// cp.cs -- Uses methods in the File class to check 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 cp.cs
using System;
using System.IO;
 
 
namespace nsStreams
{
    public class cp
    {
        static public void Main (string [] args)
        {
            if (args.Length < 2)
            {
Console.WriteLine ("usage: cp <copy from> <copy to>");
return;
            }
            if (!File.Exists (args[0]))
            {
Console.WriteLine (args[0] + " does not exist");
return;
            }
            bool bOverwrite = false;
            if (File.Exists (args[1]))
            {
Console.Write (args[1] + " already exists. Overwrite [Y/N]? ");
string reply = Console.ReadLine ();
char ch = (char) (reply[0] & (char) 0xdf);
if (ch != 'Y')
    return;
bOverwrite = true;
            }
            File.Copy (args[0], args[1], bOverwrite);
        }
    }
}

Share Article/Example:
  • DotNetKicks
  • DZone
  • StumbleUpon
  • Print
  • Add to favorites
  • Digg
  • del.icio.us
  • Twitter
  • Facebook
  • LinkedIn
  • Posterous
  • Slashdot

Filed Under: C# Streams Examples

RSSComments (0)

Trackback URL

Leave a Reply




If you want a picture to show with your comment, go get a Gravatar.