Your source for ASP-related frequently asked questions and answers! : ASP FAQS : System.IO Namespace Classes

Question: How do I determine if a file or directory exists?

Answer: Both the File and Directory classes contain an Exists() method that accepts as a single parameter the physical path to a file on the Web server's file system and returns a Boolean value indicating whether or not the file exists.

An example of using the Exists() method is shown below:

If File.Exists("C:\SomeDirectory\SomeFile.txt") then
' file exists...
' file does not exist...
End If

If Directory.Exists("C:\SomeOtherDirectory\") then ...

// C#
if (File.Exists("C:\\SomeDirectory\\SomeFile.txt")

if (Directory.Exists(@"C:\SomeOtherDirectory")

(Note that in the C# source code the backslash must be escaped by the use of two successive backslashes. However, if the string literal is preceded by an at sign (@), then escape sequences are not processed, and therefore you do not need to escape the single backslash.)

The File class is located in the System.IO namespace, meaning that you will have to import this namespace into your ASP.NET Web page or code-behind class. If you are using a server-side script block in your ASP.NET Web page, add <%@ Import Namespace="System.IO" %> to the top of the ASP.NET Web page. If you are using a code-behind class, add the following:

Imports System.IO

// C#
using System.IO;

Realize that you can easily translate a virtual path, like /files/SomeFile.aspx to its corresponding physical path, say C:\InetPub\wwwroot\files\SomeFile.aspx using the Server.MapPath() method. For more information on Server.MapPath() be sure to read Using Server.MapPath.

FAQ posted by Scott Mitchell at 9/3/2003 12:30:02 AM to the System.IO Namespace Classes category. This FAQ has been viewed 59,557 times.

Copyright 2014 QuinStreet Inc. All Rights Reserved.
Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers