Export (0) Print
Expand All

FileInfo.Exists Property

Gets a value indicating whether a file exists.

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

public override bool Exists { get; }

Property Value

Type: System.Boolean
true if the file exists; false if the file does not exist or if the file is a directory.

When first called, FileInfo calls Refresh and caches information about the file. On subsequent calls, you must call Refresh to get the latest copy of the information.

The Exists property returns false if any error occurs while trying to determine if the specified file exists. This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, a failing or missing disk, or if the caller does not have permission to read the file.

The following code example uses the Exists property ensure a file exists before opening it. You can use this technique to throw a custom exception when the file is not found.

public byte[] OpenDataFile(string FileName)
{
    // Check the FileName argument. 
    if (FileName == null || FileName.Length == 0)
    {
        throw new ArgumentNullException("FileName");
    }

    // Check to see if the file exists.
    FileInfo fInfo = new FileInfo(FileName);

    // You can throw a personalized exception if  
    // the file does not exist. 
    if (!fInfo.Exists)
    {
        throw new FileNotFoundException("The file was not found.", FileName);
    }

    // Open the file.
    FileStream fStream = new FileStream(FileName, FileMode.Open);

    // Create a buffer. 
    byte [] buffer = new byte[fStream.Length];

    // Read the file contents to the buffer.
    fStream.Read(buffer, 0, (int)fStream.Length);

    // return the buffer. 
    return buffer;

}

.NET Framework

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

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone Silverlight 8.1, Windows Phone Silverlight 8

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

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

Show:
© 2014 Microsoft