简体   繁体   中英

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

I wrote the above code using String.Concat and Path.Combine to get network path. But it is just a workaround and not a concrete solution and may fail. Is there a concrete solution for getting a network path?

You are assuming that your E:\\folder1 local path is shared as \\\\mypc\\folder1 , which in general is not true, so I doubt a general method that does what you want to do exists.

You are on the right path in implementing what you are trying to achieve. You can get more help from System.IO.Path ; see Path.GetPathRoot on MSDN for returned values according to different kind of path in input

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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