【问题标题】:`FileNotFoundException` for network-shared files that do exist. What am I missing?`FileNotFoundException` 用于确实存在的网络共享文件。我错过了什么?
【发布时间】:2015-06-14 14:26:49
【问题描述】:

我需要从共享文件中获取默认文件图标。我遇到了一些问题,发现the question "How to get the associated icon from a network share file"

但是现在我遇到了共享文件的另一个问题,看起来好像它们不存在。这是我的代码:

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;
}

我总是收到FileNotFoundException,但我现在不知道为什么。 filePath 可以,我可以通过资源管理器访问这些文件。我试图从filePath 创建FileInfo 实例(我在某处读到它可能会有所帮助)但仍然没有。

我错过了什么?

【问题讨论】:

  • 您应该可以访问网络位置,并且您的文件路径应该是这样的:\\ServerName\FolderName\FileName.txt 和 C# 中的@"\\ServerName\FolderName\FileName.txt"
  • stackoverflow.com/questions/17472168/… 的可能重复项(即使现在的问题是关于 File.Exists 而旧问题是关于 Directory.Exists)。
  • 我猜你是在像 IIS 这样的进程中运行,并且运行的权限没有网络资源的访问权限。

标签: c# network-shares


【解决方案1】:

IIRC、File.ExistsDirectory.Exists 在解析映射到网络共享的驱动器号时遇到一些问题。他们可能根本看不到这些驱动器,因此即使路径指向有效文件,他们也会报告 false

如果您使用 UNC 路径 (\\server\share\file.name) 而不是驱动器号,它可能会起作用,因此首先将基于驱动器号的文件路径解析为 UNC 路径,然后将后者传递给 File.Exists。参见例如this answerthat question 的示例如何执行此操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-26
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    相关资源
    最近更新 更多