首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将PC中的本地文件路径转换为网络相对路径或UNC路径?

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

Stack Overflow用户
提问于 2017-09-10 16:01:44
回答 1查看 1.7K关注 0票数 5
代码语言:javascript
复制
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写了上面的代码来获取网络路径。但这只是一种变通办法,而不是具体的解决方案,可能会失败。有没有一个具体的解决方案来获取网络路径?

EN

回答 1

Stack Overflow用户

发布于 2017-09-10 20:41:30

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

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

代码语言:javascript
复制
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);
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46138557

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档