技术开发 频道

根据Web应用程序绝对路径获得相对路径的函数


【IT168技术文档】

  在Web应用程序开发的时候,我们可能把一些页面地址保存到数据库中,为了在服务器端可以通过Server.Transfer等手段可以直接迁移我们使用的是应用程序绝对地址,形如“~/UIC/WebForm1.aspx”或“~/JS/Func.js”。而在我们需要通过客户端JS访问的时候我们又需要“../JS/Func.js”这样的相对路径形式,所以我写了下面代码,可以通过页面对象和请求URL的应用程序绝对地址,取得我们在客户端JS中或 HTML中使用的相对路径形式。
Public Shared Function GetRelativePath()Function GetRelativePath(ByVal page As System.Web.UI.Page, ByVal absolutePath As String) As String 2 Dim strQueryString As String = String.Empty 3 4 If page Is Nothing Then 5 Return String.Empty 6 End If 7 8 If absolutePath Is Nothing Then 9 Return String.Empty 10 End If 11 12 Dim path1 As String = page.Server.MapPath(String.Empty) & "\" 13 14 If absolutePath.LastIndexOf("?"c) > 0 Then 15 strQueryString = absolutePath.Substring(absolutePath.LastIndexOf("?"c)) 16 absolutePath = absolutePath.Substring(0, absolutePath.LastIndexOf("?"c)) 17 End If 18 19 Dim path2 As String = page.Server.MapPath(absolutePath) 20 21 Dim index As Integer = 0 22 23 If path1.IndexOf("\"c) > 0 Then 24 While (path1.IndexOf("\"c) > 0 AndAlso path1.Substring(0, path1.IndexOf("\"c)).Equals(path2.Substring(0, path1.IndexOf("\"c)))) 25 index = path1.IndexOf("\"c) 26 path1 = path1.Substring(index + 1) 27 path2 = path2.Substring(index + 1) 28 End While 29 End If 30 31 path2 = path2.Replace("\", "/") 32 33 For index = 0 To path1.Length - 1 34 If path1(index).Equals("\"c) Then 35 Dim sb As New Text.StringBuilder 36 sb.Append("../") 37 sb.Append(path2) 38 path2 = sb.ToString 39 End If 40 Next 41 42 If Not String.IsNullOrEmpty(strQueryString) Then 43 path2 = path2 & strQueryString 44 End If 45 46 Return path2 47 End Function
0
相关文章