我已经看过很多关于将相对url解析为绝对路径的教程,但我想做相反的事情:将系统绝对文件路径解析为相对URL。
是否有一种很好的无黑客方式来转换像c:\my_website_root\images\picture_a.jpg
这样的文件路径
进入images/picture_a.jpg
我看过Uri.MakeRelative()
,但我不认为在这种情况下会有用。
编辑:我已经像这样实现了它,仍然看起来像hacky(特别是第2行)
var urlPath = new Uri(@"c:\mywebfolder\images\picture1.jpg");
var urlRoot = new Uri(Server.MapPath("~")+"/");
string relative = urlRoot.MakeRelativeUri(urlPath).ToString();
答案 0 :(得分:1)
答案 1 :(得分:1)
在IIS中,设置虚拟目录images
并将其指向c:\my_website_root\images\
。
如果您的网站已经指向c:\my_website_root\
,则无需执行任何操作。
答案 2 :(得分:0)
如果您需要将所有相对网址转换为绝对网址,请使用此功能:
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