`FileNotFoundException` for network-shared files that do exist. What am I missing?

1.8k views Asked by At

I need to get a default file icon from shared file. I faced some problems with this and found the question "How to get the associated icon from a network share file".

But now I have another problem with shared files, it looks as if they did not exist. Here is my code:

public static Icon ExtractAssociatedIcon(String filePath)
{
    int index = 0;

    Uri uri;
    if (filePath == null)
    {
        throw new ArgumentException(String.Format("'{0}' is not valid for '{1}'", "null", "filePath"), "filePath");
    }
    try
    {
        uri = new Uri(filePath);
    }
    catch (UriFormatException)
    {
        filePath = Path.GetFullPath(filePath);
        uri = new Uri(filePath);
    }
    if (uri.IsFile)
    {
        if (!File.Exists(filePath))
        {
            throw new FileNotFoundException(filePath);
        }

        StringBuilder iconPath = new StringBuilder(260);
        iconPath.Append(filePath);

        IntPtr handle = SafeNativeMethods.ExtractAssociatedIcon(new HandleRef(null, IntPtr.Zero), iconPath, ref index);
        if (handle != IntPtr.Zero)
        {
            return Icon.FromHandle(handle);
        }
    }
    return null;
}

I always get FileNotFoundException and I don't now why. filePath is OK, and I can access these files through the Explorer. I tried to create FileInfo instance from filePath (I read somewhere that it may help) but still nothing.

What I'm missing?

1

There are 1 answers

0
stakx - no longer contributing On BEST ANSWER

IIRC, File.Exists and Directory.Exists have some problems resolving drive letters that are mapped to a network share. They might simply not see these drives, so they report false even though the path points to a valid file.

If you use UNC paths (\\server\share\file.name) instead of drive letters, it might work, so resolve a drive-letter-bassed file path to a UNC path first and pass the latter to File.Exists. See e.g. this answer to that question for an example how to do this.