繁体   English   中英

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

[英]How to convert a local file path in PC to a Network Relative or UNC path?

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.ConcatPath.Combine编写了上面的代码来获取网络路径。 但这只是一种解决方法,而不是具体的解决方案,可能会失败。 获取网络路径是否有具体的解决方案?

您假设您的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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM