6
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?

adiga
  • 34,372
  • 9
  • 61
  • 83
raunakchoraria
  • 358
  • 2
  • 15

1 Answers1

4

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);
}
Gian Paolo
  • 4,161
  • 4
  • 16
  • 34
  • Nice, but our solution will only work for Microsoft windows.The pattern for mac OS network path might be different than that of windows and Our solution won't work there. So is there a concrete solution provided by microsoft which will work on all possible OS. – raunakchoraria Sep 11 '17 at 17:43