Exists Property

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;


Universal Windows Platform
Available since 10
.NET Framework
Available since 1.1
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Return to top
© 2015 Microsoft