AngryHacker
AngryHacker

Reputation: 61636

Can File.Exists throw an exception?

According to the documentation, File.Exists method does not generate exceptions:

Returns 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 null, 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.

So it sounds like it doesn't throw exceptions on its own. But can a call to File.Exists result in an exception? In other words, do I need to wrap it in a try/catch?

Upvotes: 4

Views: 10006

Answers (5)

Djamil Bouchentouf
Djamil Bouchentouf

Reputation: 41

Yes, I encountered this Exception :

System.IO.PathTooLongException: 'The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.'

The Exception came from Path.GetFileName that File.Exists was calling.

Upvotes: 4

Luke Vo
Luke Vo

Reputation: 20718

No, according to the source code:

    // Tests whether a file exists. The result is true if the file
    // given by the specified path exists; otherwise, the result is
    // false.  Note that if path describes a directory,
    // Exists will return true.
    public static bool Exists(string path)
    {
        try
        {
            if (path == null)
                return false;
            if (path.Length == 0)
                return false;

            path = Path.GetFullPath(path);

            // After normalizing, check whether path ends in directory separator.
            // Otherwise, FillAttributeInfo removes it and we may return a false positive.
            // GetFullPath should never return null
            Debug.Assert(path != null, "File.Exists: GetFullPath returned null");
            if (path.Length > 0 && PathInternal.IsDirectorySeparator(path[path.Length - 1]))
            {
                return false;
            }

            return FileSystem.FileExists(path);
        }
        catch (ArgumentException) { }
        catch (IOException) { }
        catch (UnauthorizedAccessException) { }

        return false;
    }

There isn't seem to be any case the it should throw an Exception unless FileSystem.FileExists throws some exception I don't know about.

EDIT: Since I cannot find out source code of FileSystem.FileExists, I checked the .NET Framework source code instead, it's a bit different at the internal call:

    // Determine whether path describes an existing directory
    // on disk, avoiding security checks.
    [System.Security.SecurityCritical]  // auto-generated
    [ResourceExposure(ResourceScope.Machine)]
    [ResourceConsumption(ResourceScope.Machine)]
    internal static bool InternalExists(String path, out int lastError) {
        Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
        lastError = File.FillAttributeInfo(path, ref data, false, true);

        return (lastError == 0) && (data.fileAttributes != -1)
                && ((data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) != 0);
    }

It in turn calls FillAttributeInfo (the code is a bit long so I don't paste it here), I think it only throws IOException (at line 1402 __Error.WinIOError();)

Upvotes: 10

Stefan
Stefan

Reputation: 17658

Yes it can raise exceptions.

E.g.: OutOfMemoryException.

These kind of exception might not be thrown by the code itself, but might be thrown as a side effect of executing it.

The same woud apply for the infamous StackOverflowException, or also, more low level exceptions maybe due to failing hardware.

I am unaware of the total listing; but I am sure; calling the code can lead to exceptions being raised.

As @Otis notes: it will be difficult to recover from those kind of exceptions. So, even if they are raised: often a try/catch will not be sufficient.

So, to sum it:

can a call to File.Exists result in an exception?

Yes

In other words, do I need to wrap it in a try/catch?

Another question, but, presumably not.

Upvotes: 0

Christopher
Christopher

Reputation: 9824

Everything can result in a Exception. Even if the code itself does not throw one, what if you run into a Fatal Exception like OutOfMemory or ThreadAborted?

This sounds like it is primarily a question about Exception handling, and for those questions I have two articles that I link often:

If you want to learn how to deal with exceptions, they are a very good start.

Upvotes: 5

Otis
Otis

Reputation: 1072

There are no exceptions listed in the documentation for that method, which implies no exceptions should be thrown. In fact, further down it mentions that "false" will be returned if an exception would have been thrown trying to access the file.

Upvotes: 0

Related Questions