Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将PC中的本地文件路径转换为网络相对路径或UNC路径?_C#_Vb.net - Fatal编程技术网

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

C# 如何将PC中的本地文件路径转换为网络相对路径或UNC路径?,c#,vb.net,C#,Vb.net,我使用String.Concat和Path.Combine编写了上述代码,以获得网络路径。但这只是一个权宜之计,不是一个具体的解决方案,可能会失败。 是否有一个具体的解决方案来获取网络路径?您假设您的E:\folder1本地路径被共享为\\mypc\folder1,这通常是不正确的,因此我怀疑是否存在一个通用方法来实现您想要的操作 你正走在正确的道路上实现你想要实现的目标。您可以从System.IO.Path获得更多帮助;请参阅上的Path.GetPathRoot,了解根据输入中不同类型的路径返

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

您假设您的
E:\folder1
本地路径被共享为
\\mypc\folder1
,这通常是不正确的,因此我怀疑是否存在一个通用方法来实现您想要的操作

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

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);

很好,但是我们的解决方案只适用于Microsoft windows。mac OS网络路径的模式可能与windows不同,我们的解决方案在那里不起作用。那么,微软是否提供了一个具体的解决方案,可以在所有可能的操作系统上运行呢。
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);
}