1

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?

Community
  • 1
  • 1
alexlz
  • 618
  • 1
  • 10
  • 24
  • 1
    you should have access to Network location as well as your file path should be something like this: `\\ServerName\FolderName\FileName.txt` and in C# `@"\\ServerName\FolderName\FileName.txt"` – Dgan Jun 14 '15 at 14:33
  • Possible duplicate of http://stackoverflow.com/questions/17472168/check-if-directory-exists-on-network-drive (even though the present question is about `File.Exists` and the older question is about `Directory.Exists`). – stakx - no longer contributing Jun 14 '15 at 14:34
  • I'm going to guess that your running in a process like IIS and that runs with privileges that don't have access to network resources. – kenny Jun 14 '15 at 14:52

1 Answers1

2

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.

Community
  • 1
  • 1
stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268