【问题标题】:How to convert an URL absolute path to relative path如何将 URL 绝对路径转换为相对路径
【发布时间】:2015-01-24 23:52:20
【问题描述】:

例如,我有:

string AbsImgURL = "~/MyStuff/Images/MsgBoxIcon/MyImg.jpg";

我希望它是:

string AbsImgURL = "../../MyStuff/Images/MsgBoxIcon/MyImg.jpg"

(因为我目前在页面“~/UI/Pages/Default.aspx”,距离根目录深两级)

【问题讨论】:

  • VirtualPathUtility 有什么问题?
  • Brad:我第一次听说,能告诉我怎么做吗?
  • 你试过VirtualPathUtility.MakeReleative
  • Ben:请举例说明如何使用它。
  • 我可以为你写一个算法,但是 Ben 的方法要容易得多。

标签: c# asp.net relative-path absolute-path


【解决方案1】:

谢谢家伙,我终于通过使用 VirtualPathUtility.MakeRelative 让它工作了。代码如下:

     /// <summary>Convert and URL Absoluate Path to Relative Path 
     ///(For Example: "~/MyStuff/Images/MsgBoxIcon/MyImg.jpg" ==> "../../MyStuff/Images/MsgBoxIcon/MyImg.jpg"
     ///(Assuming client is currently at the page "~/UI/Pages/Default.aspx", which is two level deep from the root).</summary>
    private static string ConvertAbsoluteToRelativePath(string Input)
    {
        //Init
        string Output = "";

        //Get Current URL (Ex: http://MyWebSite//...)
        string CurrentURL = HttpContext.Current.Request.Url.AbsolutePath;

        //Convert to Relative Path
        Output = VirtualPathUtility.MakeRelative(CurrentURL, Input);

        //Finally
        return Output;
    }

【讨论】:

    猜你喜欢
    • 2017-08-01
    • 2011-11-07
    • 2011-05-02
    • 1970-01-01
    相关资源
    最近更新 更多