回答
没有属性,但它不是太难解析出来:
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];
}
如果您确定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的查询字符串中添加了一些垃圾,以便在追加参数时证明它仍然有效。
简单字符串操作怎么样?
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'
试试这个(没有字符串操作):
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);
我有非常类似的东西,但我喜欢这么多,因为它有一个较少的函数调用! – 2009-10-23 23:44:32
这一块石头! – 2011-11-04 09:13:50
真不错的方法!如果基地址是一个目录,则需要使用“..”而不是“。”。此外,在这种情况下,请小心,因为如果尝试获取根目录的父级,则不会发生异常;你刚刚得到相同的Uri。 – 2012-12-14 00:31:06
这里是做的非常干净的方式。还有一个优点,就是可以使用任何网址:
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这是我在那里验证此!)
转储()做什么?此解决方案不在此编译。 – pyrocumulus 2009-10-23 23:35:00
虽然没有转储()调用,但工作良好。 +1有一个很好的干净的解决方案,适用于每个网址(即使没有文件名)。 – pyrocumulus 2009-10-23 23:36:29
没有更多的投票了:| – pyrocumulus 2009-10-23 23:38:13
- 1. 我怎样才能得到一个TD
- 2. 我怎样才能得到一个RejectedExecutionException
- 3. 我怎样才能得到一个PortletRequest
- 4. 我怎样才能得到
- 5. 我怎样才能得到
- 6. 我怎样才能找到一个动态目录在.htaccess
- 7. 我怎样才能得到R当前文件目录
- 8. 我怎样才能从xmlnodereader得到一个xmlnode
- 9. 我怎样才能得到一个JSON像这样用JavaScript
- 10. 我怎样才能找到一个DataTable
- 11. 我怎样才能得到第一级的项目?
- 12. 我怎样才能得到一个文件夹的目录,然后它的目录的目录等......?
- 13. 我怎样才能得到Parsley.js
- 14. 我怎样才能得到Queryable.Join的MethodInfo
- 15. 我怎样才能得到父组件
- 16. 我怎样才能得到的数字
- 17. 我怎样才能得到statechange
- 18. 我怎样才能得到这些值
- 19. 我怎样才能得到其他表
- 20. 我怎样才能得到NSScrollView尊重
- 21. regmatch_t我怎样才能得到匹配?
- 22. 我怎样才能得到在Android的
- 23. 我怎样才能得到用户
- 24. 我怎样才能得到JSON fton WebSQL
- 25. 我怎样才能得到结果?
- 26. 我怎样才能得到屏幕-Android
- 27. 我怎样才能得到facebook-sdk oauth_access_token
- 28. rootObj replaceObjectAtIndex,我怎样才能得到valueForKey?
- 29. 我怎样才能得到`在centOS6
- 30. 我怎样才能得到android
检查Rubens Farias的答案在下面,因为它比这个好得多。 – bigbearzhu 2015-08-07 04:40:20