How can I get a directory from a Uri

Try this (without string manipulation):

Uri baseAddress = new Uri("http://www.example.com/mydirectory/myfile.aspx?id=1");
Uri directory = new Uri(baseAddress, "."); // "." == current dir, like MS-DOS
Console.WriteLine(directory.OriginalString);

Here's a pretty clean way of doing it. Also has the advantage of taking any url you can throw at it:

var uri = new Uri("http://www.example.com/mydirectory/myfile.aspx?test=1");
var newUri = new Uri(uri, System.IO.Path.GetDirectoryName(uri.AbsolutePath));

NOTE: removed Dump() method. (It's from LINQPad which was where I was verifying this!)

Tags:

.Net