Question

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();
Was it helpful?

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

OTHER TIPS

Try this using string.Format method;

string path = @"\\server1\folder\child";
string server = "server2";
string newPath = string.Format(@"\{0}\{1}" + server + @"\{3}\{4}", 
                               path.Split('\\'));

Or this using Substring and IndexOf methods;

string s = @"\\server1\folder\child";
string server = @"\\server2";
string s2 = server + s.Substring( s.Substring(2).IndexOf(@"\")+2);

I'm not sure what you tried with Regexes, but I think this should basically do what you're looking for:

var path = @"\\server1\folder\child";
var replaced = Regex.Replace(path, @"\\\\[A-Za-z0-9]*\\", @"\\server2\");
string ReplaceServer(string path, string newServer)
    {
        return path.Replace(path.Split('\\')[2], newServer);
    }

And to prove that there's a thousand different ways to skin the cat:

string oldPath = "\\testserver1\\folder\\child";    
string newServer ="testserver2";
var subPath = oldPath.Split(new []{'\\'},StringSplitOptions.RemoveEmptyEntries)
    .Skip(1)
    .Take(Int32.MaxValue)
    .ToList();
subPath.Insert(0,newServer);
var newPath = Path.Combine(subPath.ToArray());
newPath = @"\\"+newPath;
newPath.Dump();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top