Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

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?

like image 982
rrc1709 Avatar asked Oct 29 '22 02:10

rrc1709


1 Answers

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);
}
like image 171
Gian Paolo Avatar answered Nov 14 '22 06:11

Gian Paolo