如何在C#中获取URL路径 [英] How to get URL path in C#

查看:478
本文介绍了如何在C#中获取URL路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了URL的当前页面外,我想获取URL的所有路径,例如:我的URL是 http ://www.MyIpAddress.com/red/green/default.aspx 我想获取 http://仅www.MyIpAddress.com/red/green/ 。我该怎么办

I want to get the all the path of URL except the current page of url, eg: my URL is http://www.MyIpAddress.com/red/green/default.aspx I want to get "http://www.MyIpAddress.com/red/green/" only. How can I get.I'm doing like

string sPath = new Uri(HttpContext.Current.Request.Url.AbsoluteUri).OriginalString; System.Web.HttpContext.Current.Request.Url.AbsolutePath;
            sPath = sPath.Replace("http://", "");
            System.IO.FileInfo oInfo = new System.IO.FileInfo(sPath);
            string sRet = oInfo.Name;
            Response.Write(sPath.Replace(sRet, ""));

它在新的System.IO.FileInfo(sPath)上显示异常,因为sPath包含 localhost / red / green / default.aspx说不支持给定路径的格式。

Its showing exception on new System.IO.FileInfo(sPath) as sPath contain "localhost/red/green/default.aspx" saying "The given path's format is not supported."

推荐答案

请勿将其视为URI问题,将其视为字符串问题。

Don't treat it as a URI problem, treat it a string problem. Then it's nice and easy.

String originalPath = new Uri(HttpContext.Current.Request.Url.AbsoluteUri).OriginalString;
String parentDirectory = originalPath.Substring(0, originalPath.LastIndexOf("/"));

真的很简单!

已编辑添加缺少的括号。

Edited to add missing parenthesis.

这篇关于如何在C#中获取URL路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆