【问题标题】:How to convert a local file path in PC to a Network Relative or UNC path?如何将 PC 中的本地文件路径转换为网络相对路径或 UNC 路径?
【发布时间】:2017-09-10 08:01:43
【问题描述】:
String machineName = System.Environment.MachineName;
String filePath = @"E:\folder1\folder2\file1";
int a = filePath.IndexOf(System.IO.Path.DirectorySeparatorChar);
filePath = filePath.Substring(filePath.IndexOf(System.IO.Path.DirectorySeparatorChar) +1);
String networdPath = System.IO.Path.Combine(string.Concat(System.IO.Path.DirectorySeparatorChar, System.IO.Path.DirectorySeparatorChar), machineName, filePath);
Console.WriteLine(networdPath);

我使用String.Concat 和Path.Combine 编写了上面的代码来获取网络路径。但这只是一种解决方法,而不是具体的解决方案,可能会失败。 有没有获取网络路径的具体解决方案?

【问题讨论】:

标签: c# vb.net


【解决方案1】:

您假设您的 E:\folder1 本地路径共享为 \\mypc\folder1,这通常不正确,所以我怀疑是否存在可以执行您想做的事情的通用方法。

您在实现您想要实现的目标方面走在正确的道路上。您可以从System.IO.Path获得更多帮助;请参阅MSDN 上的Path.GetPathRoot,了解根据输入中不同类型路径的返回值

string GetNetworkPath(string path)
{
    string root = Path.GetPathRoot(path);

    // validate input, in your case you are expecting a path starting with a root of type "E:\"
    // see Path.GetPathRoot on MSDN for returned values
    if (string.IsNullOrWhiteSpace(root) || !root.Contains(":"))
    {
        // handle invalid input the way you prefer
        // I would throw!
        throw new ApplicationException("be gentle, pass to this function the expected kind of path!");
    }
    path = path.Remove(0, root.Length);
    return Path.Combine(@"\\myPc", path);
}

【讨论】:

  • 很好,但我们的解决方案仅适用于 Microsoft windows。mac OS 网络路径的模式可能与 windows 不同,我们的解决方案不适用于那里。那么微软是否提供了适用于所有可能操作系统的具体解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-22
  • 2011-01-19
  • 1970-01-01
  • 1970-01-01
  • 2013-01-23
  • 2014-04-27
相关资源
最近更新 更多