开发者

How can I get a directory from a Uri

For example, if I have

http://www.example.com/my开发者_Python百科directory/myfile.aspx

How can I get

http://www.example.com/mydirectory

I am looking for a .NET function call.


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


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

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


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.example.com/mydirectory/myfile.aspx"));
// newUri is now 'http://www.example.com/mydirectory'


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.example.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.example.com/mydirectory

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜