如何从Uri获取目录

时间:2009-10-23 23:02:05

标签: .net

例如,如果我有

  

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

我怎样才能获得

  

http://www.example.com/mydirectory

我正在寻找一个.NET函数调用。

5 个答案:

答案 0 :(得分:43)

试试这个(没有字符串操作):

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

答案 1 :(得分:13)

这是一种非常干净的方式。还有一个优点,就是你可以扔任何网址:

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

注意:删除了Dump()方法。 (它来自LINQPad,我正在验证这个!)

答案 2 :(得分:1)

简单的字符串操作怎么样?

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'

答案 3 :(得分:1)

没有财产,但解析它并不困难:

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];
}

答案 4 :(得分:0)

如果您确定文件名位于URL的末尾,则以下代码将起作用。

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

我在URL的查询字符串中添加了一些垃圾,以证明在附加参数时它仍然有效。

相关问题