tags:

views:

187

answers:

6

For emample, if I have

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

How can I get

http://www.mysite.com/mydirectory

I am looking for a .NET function call.

+1  A: 

The method Uri.GetLeftPart(..) is a good starting point. See the MSDN article.

Scooterville
It's a good start but it does not answer my question.
tom greene
A: 

If you're sure a filename is on the end of the URL the following code will work.

using System;
using System.IO;

Uri u = new Uri(@"http://www.mysite.com/mydirectory/myfile.aspx?v=1&t=2");

//Ensure trailing querystring, hash, etc are removed
string strUrlCleaned = u.GetLeftPart(UriPartial.Path); 
// Get only filename
string strFilenamePart = Path.GetFileName(strUrlCleaned); 
// Strip filename off end of the cleaned URL including trailing slash.
string strUrlPath = strUrlCleaned.Substring(0, strUrlCleaned.Length-strFilenamePart.Length-1);

MessageBox.Show(strUrlPath); 
// shows: http://www.mysite.com/mydirectory

I added some junk to the querystring of the URL to prove it still works when parameters are appended.

John K
+1  A: 

What about simple string manipulation?

public static Uri GetDirectory(Uri input) {
    string path = input.GetLeftPart(UriPartial.Path);
    return new Uri(path.Substring(0, path.LastIndexOf('/')));
}

// ...
newUri = GetDirectory(new Uri ("http://www.mysite.com/mydirectory/myfile.aspx"));
// newUri is now 'http://www.mysite.com/mydirectory'
CMS
+9  A: 

Try this (without string manipulation):

Uri baseAddress = new Uri("http://www.mysite.com/mydirectory/myfile.aspx?id=1");
Uri directory = new Uri(baseAddress, "."); // "." == current dir, like MS-DOS
Console.WriteLine(directory.OriginalString);
Rubens Farias
I had something very similar, but I like this much, better since it has one less function call!
Josh
+1  A: 

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

Josh
What does Dump() do? This solution does not compile here.
Cloud
Works well without the Dump() call though. +1 for having a nice clean solution that works for every url (even without a filename).
Cloud
No more votes left :|
Cloud
Erm....haha silly testing ground statements! Dump() is an internal method for LINQPad which is where I usually test things before posting them!
Josh
+1  A: 

There is no property but it isn't too hard to parse it out:

Uri uri = new Uri("http://www.mysite.com/mydirectory/myfile.aspx");
string[] parts = uri.LocalPath.Split('/');
if(parts.Length >= parts.Length - 2){
     string directoryName = parts[parts.Length - 2];
}

robb

Robb C