12.2 Verifying the Existence of a File

 <  Day Day Up  >  

You want to verify that a file exists given the path to that file.


Technique

The File class contains a method named Exists , which returns a Boolean value:

 
 if( File.Exists( file ) ) {     File.Delete( file ); } 

Comments

The Exists method returns true if a file exists at a specified location or false if it doesn't. However, if the current security permissions on the file don't allow the user to access it, the Exists method returns false even though the file does exist.

The path to the file can be either a relative or absolute path. An absolute path is the full path of the file starting from the drive letter. A file named file.txt located in the temp directory of the hard drive therefore has an absolute path of

 
 c:\temp\file.txt 

A relative path means the file is relative to a certain location. This location is the current directory of the operating system. Take note that it isn't always the directory your application is running in. To determine the current directory, call the static method Directory.GetCurrentDirectory . If you do in fact want to retrieve the directory that your application is running from, call the static method Application.StartupPath . An example of an app trying to discover the existence of itself includes code such as the following:

 
 Directory.SetCurrentDirectory( Application.StartupPath ); if( File.Exists("1_FileView.exe ") ) {     MessageBox.Show( "I Am" ); } 
 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net