Recipe12.4.Determining Whether a File Exists


Recipe 12.4. Determining Whether a File Exists

Problem

You need to determine whether a file exists prior to creating or performing an action on that file.

Solution

Use the static Exists method of the File class to determine whether a file currently exists:

 if (File.Exists(@"c:\delete\test\test.txt")) {     // Operate on that file here. } 

Discussion

Determining whether a file exists is often critical to your code. If a file exists and you try to create it using one of the file-creation methods, one of three things will happen: the existing file will be overwritten, an exception will be thrown if the file is read-only, or an exception will be thrown indicating that the state of the filesystem is not what you think it is. There is a small window between the Exists call and the actions you take where another process could change the filesystem, so you should be prepared for that with proper exception handling.

See Also

See the "File Class" topic in the MSDN documentation.



C# Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2004
Pages: 424

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