7

I've seen lots of tutorials on resolving a relative url to an absolute path, but i want to do the opposite: resolve an system absolute filepath into a relative url.

Is there a nice hack-free way to turn a filepath like c:\my_website_root\images\picture_a.jpg into images/picture_a.jpg

I've had a look at Uri.MakeRelative() but i dont think it will be of use in this case.

Edit: I've implemented it like this, still seems 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();
Crono
  • 10,211
  • 6
  • 43
  • 75
maxp
  • 24,209
  • 39
  • 123
  • 201

2 Answers2

1

In IIS, setup a virtual directory images and point it to c:\my_website_root\images\.

If your website is already directing to c:\my_website_root\, you don't need to do anything.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
0

If you need to convert all the relative urls to absolute urls use this fucntion:

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
Brad Larson
  • 170,088
  • 45
  • 397
  • 571
Mahmoud
  • 1
  • 1