【问题标题】:Return network name from file path [duplicate]从文件路径返回网络名称[重复]
【发布时间】:2021-01-18 11:20:01
【问题描述】:

我遇到了一个问题,当用户将文件目录添加到我的项目时,链接将存储为他们自己的映射驱动器。例如;

C:\Location\Location

但是,例如,某些用户可能会将服务器上的 C: 驱动器映射为 M:。因此无法找到该文件。

我想做的是用实际的服务器名称替换它,即

\\ArtServer\

我知道我可以通过替换字符串的开头部分来实现这一点,但是如果将来添加更多服务器,那么这显然会陷入混乱。目前,用户使用标准的获取文件对话框获取文件路径;

public static string GetFilePath(string filter = "All Files (*.*)|*.*", string initialDirectory = @"This PC")
{
    OpenFileDialog fileDialog = new OpenFileDialog();
    fileDialog.Filter = filter;
    fileDialog.FilterIndex = 1;
    fileDialog.Multiselect = false;

    fileDialog.InitialDirectory = Directory.Exists(initialDirectory) ? initialDirectory : @"This PC";

    if (fileDialog.ShowDialog() == true)
    {
        return fileDialog.FileName;
    }
    else
    {
        return null;
    }
}

无论如何我可以用我目前拥有的东西来实现这一目标吗?

【问题讨论】:

  • 你的目的是什么?如果您只是将 C:\Location\Location 更改为 \\ArtServer\Location\Location 并希望它能够正常工作 - 您需要确保您的 ArtServer 上有 Location 共享并且您当前的用户可以访问它
  • 另外,在某些情况下\\ArtServer\C$\Location\Location 可能会起作用
  • 我们看到的主要用例是,如果有人将文件目录添加到系统中,则有权访问该服务器路径的用户无法打开该文件,因为他们的本地系统正在寻找对于 C:其中添加到系统的链接可能是 M:例如。作为快速修复,我已经更改了它,以便当用户添加墨迹时,字符串的第一部分将替换为服务器名称,但是我不认为这很好,因为最终引入了更多服务器
  • @ADyson 感谢您添加该参考,这非常有帮助!我很抱歉提出这个问题,但我注意到 ibram 中途的一个回答讨论了一个用例,其中使用 System.Management 更受欢迎,因为我想尽可能地避开外部 DLL。但是,您知道如何使用文件对话来实现吗?我讨厌要求代码,但我真的很难理解如何将其实现为我需要的东西
  • 我对 WPF 或其对话框一无所知,但假设您可以从对话框中获取路径,那么我猜您只需将该路径传递给 GetUNCPath 方法例如,然后在您保存的数据中使用结果。

标签: c# wpf


【解决方案1】:

感谢@ADyson 提供的所有帮助。我决定使用上面链接的线程中 ibram 提供的答案。对于其他有同样问题的人,我已经发布了我所做的;

public static string GetUNCPath(string path)
{
    if (path.StartsWith(@"\\"))
    {
        return path;
    }

    ManagementObject mo = new ManagementObject();
    mo.Path = new ManagementPath(String.Format("Win32_LogicalDisk='{0}'", path));

    // DriveType 4 = Network Drive
    if (Convert.ToUInt32(mo["DriveType"]) == 4)
    {
        return Convert.ToString(mo["ProviderName"]);
    }
    else
    {
        return path;
    }
}

public static string GetFilePath(string filter = "All Files (*.*)|*.*", string initialDirectory = @"This PC")
{
    OpenFileDialog fileDialog = new OpenFileDialog();
    fileDialog.Filter = filter;
    fileDialog.FilterIndex = 1;
    fileDialog.Multiselect = false;

    fileDialog.InitialDirectory = Directory.Exists(initialDirectory) ? initialDirectory : @"This PC";

    if (fileDialog.ShowDialog() == true)
    {
        // Split the file directory to gain root path
        // Use GetUNCPath to convert root path to server name
        string s = fileDialog.FileName;
        int index = s.IndexOf(':') + 1;
        string rootPath = GetUNCPath(s.Substring(0, index));
        string directory = s.Substring(index);
        return rootPath + directory;
    }
    else
    {
        return null;
    }
}

【讨论】:

    猜你喜欢
    • 2019-03-30
    • 2021-06-01
    • 1970-01-01
    • 2014-01-28
    • 2020-03-16
    • 2014-04-08
    • 1970-01-01
    • 2011-09-26
    相关资源
    最近更新 更多