7

我看过很多关于将相对 url 解析为绝对路径的教程,但我想做相反的事情:将系统绝对文件路径解析为相对 url。

有没有一种很好的免破解方法可以将文件路径c:\my_website_root\images\picture_a.jpg 转换为images/picture_a.jpg

我已经看过了,Uri.MakeRelative()但我认为在这种情况下它不会有用。

编辑:我已经这样实现了,仍然看起来很hacky(esp line#2)

var urlPath = new Uri(@"c:\mywebfolder\images\picture1.jpg");
var urlRoot = new Uri(Server.MapPath("~")+"/");
string relative = urlRoot.MakeRelativeUri(urlPath).ToString();
4

2 回答 2

1

在 IIS 中,设置一个虚拟目录images并将其指向c:\my_website_root\images\.

如果您的网站已经指向c:\my_website_root\,则无需执行任何操作。

于 2010-02-01T10:57:14.703 回答
0

如果您需要将所有相对 url 转换为绝对 url,请使用以下功能:

Private Function ConvertALLrelativeLinksToAbsoluteUri(ByVal html As String, ByVal PageURL As String)
    Dim result As String = Nothing

    ' Getting all Href
    Dim opt As New RegexOptions

    Dim XpHref As New Regex("(href="".*?"")", RegexOptions.IgnoreCase)

    Dim i As Integer
    Dim NewSTR As String = html
    For i = 0 To XpHref.Matches(html).Count - 1
        Application.DoEvents()
        Dim Oldurl As String = Nothing
        Dim OldHREF As String = Nothing
        Dim MainURL As New Uri(PageURL)
        OldHREF = XpHref.Matches(html).Item(i).Value
        Oldurl = OldHREF.Replace("href=", "").Replace("HREF=", "").Replace("""", "")
        Dim NEWURL As New Uri(MainURL, Oldurl)
        Dim NewHREF As String = "href=""" & NEWURL.AbsoluteUri & """"
        NewSTR = NewSTR.Replace(OldHREF, NewHREF)


    Next

    html = NewSTR

    Dim XpSRC As New Regex("(src="".*?"")", RegexOptions.IgnoreCase)

    For i = 0 To XpSRC.Matches(html).Count - 1
        Application.DoEvents()
        Dim Oldurl As String = Nothing
        Dim OldHREF As String = Nothing
        Dim MainURL As New Uri(PageURL)
        OldHREF = XpSRC.Matches(html).Item(i).Value
        Oldurl = OldHREF.Replace("src=", "").Replace("src=", "").Replace("""", "")
        Dim NEWURL As New Uri(MainURL, Oldurl)
        Dim NewHREF As String = "src=""" & NEWURL.AbsoluteUri & """"
        NewSTR = NewSTR.Replace(OldHREF, NewHREF)


    Next


    Return NewSTR


End Function
于 2014-02-20T19:50:14.663 回答