如何将 PC 中的本地文件路径转换为网络相对路径或 UNC 路径?

rrc*_*709 5 c# vb.net

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);
Run Code Online (Sandbox Code Playgroud)

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

Gia*_*olo 4

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

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

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);
}
Run Code Online (Sandbox Code Playgroud)