2010-02-01 291 views
7

我已經看到很多關於將相對url解析爲絕對路徑的教程,但我想做相反的事情:將系統絕對文件路徑解析爲相對url。相對URL的絕對文件路徑

是否有一個很好的免費下鍋的辦法把像c:\my_website_root\images\picture_a.jpg 文件路徑爲images/picture_a.jpg

我看了一下Uri.MakeRelative(),但我不認爲這將是在這種情況下使用的。

編輯:我已經實現了它這個樣子,似乎仍然哈克(ESP生產線#2)

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

回答

1

在IIS,設置虛擬目錄images和點它到c:\my_website_root\images\

如果您的網站已經指向c:\my_website_root\,則無需執行任何操作。

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 
+2

一些可能的解釋一路上去改善這個答案。 – 2014-03-11 19:49:03