Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

11.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: either the existing file will be overwritten; or, if the file is read-only, an exception will be thrown; 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.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata