Search code examples
c#uncreplace

Replace the ServerName in a UNC Path


I want to write a method to swap out the server name in a UNC path. So if I have "\\server1\folder\child" I want to swap in "\\server2\folder\child". Various attempts to do this have run into jagged edges with .net's handling of backslashes (regex, Path.Combine). I will not know the name of "server1" at runtime.

Here's a snippet I have been testing in LinqPad, while it works it seems pretty hacky:

string path = @"\\server1\folder\child";

var uri = new Uri(path);

string newPath = @"\\server2\";

foreach (var part in uri.Segments)
{
 if (part == "/")
     continue;

 newPath += part;
}

var x = new Uri(newPath);

uri.Dump();

x.LocalPath.Dump();

Solution

  • You were on the right path (no pun intended)

    Quick edit of your code leaves this:

    string path = @"\\server1\folder\child";
    
    var uri = new Uri(path);
    
    string newPath = @"\\server2" + uri.AbsolutePath.Replace('/', '\\');
    
    var x = new Uri(newPath);