Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
.NET Framework 3.5
System.IO Namespace
File Class
File Methods
 Exists Method
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
.NET Framework Class Library
File..::.Exists Method

Updated: November 2007

Determines whether the specified file exists.

Namespace:  System.IO
Assembly:  mscorlib (in mscorlib.dll)

Visual Basic (Declaration)
Public Shared Function Exists ( _
    path As String _
) As Boolean
Visual Basic (Usage)
Dim path As String
Dim returnValue As Boolean

returnValue = File.Exists(path)
C#
public static bool Exists(
    string path
)
Visual C++
public:
static bool Exists(
    String^ path
)
J#
public static boolean Exists(
    String path
)
JScript
public static function Exists(
    path : String
) : boolean

Parameters

path
Type: System..::.String

The file to check.

Return Value

Type: System..::.Boolean

true if the caller has the required permissions and path contains the name of an existing file; otherwise, false. This method also returns false if path is nullNothingnullptra null reference (Nothing in Visual Basic), an invalid path, or a zero-length string. If the caller does not have sufficient permissions to read the specified file, no exception is thrown and the method returns false regardless of the existence of path.

The Exists method should not be used for path validation, this method merely checks if the file specified in path exists. Passing an invalid path to Existsl returns false.

Be aware that another process can potentially do something with the file in between the time you call the Exists method and perform another operation on the file, such as Delete. A recommended programming practice is to wrap the Exists method, and the operations you take on the file, in a try...catch block as shown in the example. This helps to narrow the scope for potential conflicts. The Exists method can only help to ensure that the file will be available, it cannot guarantee it.

The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see GetCurrentDirectory.

If path describes a directory, this method returns false. Trailing spaces are removed from the path parameter before determining if the file exists.

The following example uses the Exists method to help ensure that a file is not overwritten.

Visual Basic
Imports System
Imports System.IO
Imports System.Text

Public Class Test
    Public Shared Sub Main()
        Dim path As String = "c:\temp\MyTest.txt"
        Dim path2 As String = path + "temp"
        Try
            Dim sw As StreamWriter = File.CreateText(path)
            sw.Close()
            ' Do the Copy operation only if the first file exists
            ' and the second file does not.
            If File.Exists(path) Then
                If File.Exists(path2) Then
                    Console.WriteLine("The target file already exists.")
                Else
                    'try to copy it
                    File.Copy(path, path2)
                    Console.WriteLine("{0} was copied to {1}.", path, path2)
                End If
            Else
                Console.WriteLine("The source file does not exist.")
            End If
        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class

C#
using System;
using System.IO;

class Test 
{
    public static void Main() 
    {
        string path = @"c:\temp\MyTest.txt";
        string path2 = path + "temp";
        try 
        {
            using (StreamWriter sw = File.CreateText(path)) {}

            // Only do the Copy operation if the first file exists
            // and the second file does not.
            if (File.Exists(path)) 
            {
                if (File.Exists(path2)) 
                {
                    Console.WriteLine("The target already exists");
                } 
                else 
                {
                    // Try to copy the file.
                    File.Copy(path, path2);
                    Console.WriteLine("{0} was copied to {1}.", path, path2);
                }
            } 
            else 
            {
                Console.WriteLine("The source file does not exist.");
            }
        } 
        catch 
        {
            Console.WriteLine("Double copying is not allowed, as expected.");
        }
    }
}

Visual C++
using namespace System;
using namespace System::IO;

int main()
{
   String^ path = "c:\\temp\\MyTest.txt";
   String^ path2 = String::Concat( path, "temp" );
   try
   {
      StreamWriter^ sw = File::CreateText( path );
      if ( sw )
            delete (IDisposable^)sw;

      // Only do the Copy operation if the first file exists
      // and the second file does not.
      if ( File::Exists( path ) )
      {
         if ( File::Exists( path2 ) )
         {
            Console::WriteLine( "The target already exists" );
         }
         else
         {
            // Try to copy the file.
            File::Copy( path, path2 );
            Console::WriteLine( "{0} was copied to {1}.", path, path2 );
         }
      }
      else
      {
         Console::WriteLine( "The source file does not exist." );
      }
   }
   catch ( Exception^ ) 
   {
      Console::WriteLine( "Double copying is not allowed, as expected." );
   }
}

J#
import System.*;
import System.IO.*;

class Test
{
    public static void main(String[] args)
    {
        String path = "c:\\temp\\MyTest.txt";
        String path2 = path + "temp";

        try {            
            StreamWriter sw = File.CreateText(path);
            try {
            }
            finally {
                sw.Dispose();
            }

            // Only do the Copy operation if the first file exists
            // and the second file does not.
            if (File.Exists(path)) {
                if (File.Exists(path2)) {
                    Console.WriteLine("The target already exists");
                }
                else {
                    // Try to copy the file.
                    File.Copy(path, path2);
                    Console.WriteLine("{0} was copied to {1}.", path, path2);
                }
            }
            else {
                Console.WriteLine("The source file does not exist.");
            }
        }
        catch (System.Exception exp) {
            Console.WriteLine("Double copying is not allowed, as expected.");
        }
    } //main
} //Test

Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 3.5, 2.0, 1.0

XNA Framework

Supported in: 2.0, 1.0
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2008 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker