Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a directory from a Uri

Tags:

.net

For example, if I have

http://www.example.com/mydirectory/myfile.aspx

How can I get

http://www.example.com/mydirectory

I am looking for a .NET function call.

like image 674
tom greene Avatar asked Oct 23 '09 23:10

tom greene


2 Answers

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);
like image 117
Rubens Farias Avatar answered Nov 10 '22 03:11

Rubens Farias


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

like image 30
Joshua Shannon Avatar answered Nov 10 '22 02:11

Joshua Shannon