新的Uri保留逃脱的角色

时间:2012-04-10 06:35:45

标签: .net uri special-characters

我想从包含转义字符的字符串中实例化一个新的Uri。

Dim sUri as String = "http://foo.bar/path/to/file_with%2fpercent?query=params"
Dim uUri as New Uri(sUri)
Console.WriteLine(uUri)

>>>>

http://foo.bar/path/to/file_with/percent?query=params

如何保留%2f

1 个答案:

答案 0 :(得分:0)

使用例如以下代码(注意:仅适用于绝对URL!):

Sub DownloadFileToDisc (downloadUrl As String)
    Dim MyWebClient As New System.Net.WebClient()
    Dim downloadUri As New UriWithCorrectDataEncoding(downloadUrl)
    MyWebClient.DownloadFile(downloadUri, localFilePath)
End Sub

''' <summary>
''' Original behaviour of System.Uri.ToString returns unescaped characters in query parameters - a behaviour which corrupts URLs like http://domain.com/?forwardurl=module%3dInvoice%26action%3dCreatePDF4Mail%26return_module%3dInvoice into http://domain.com/?forwardurl=module=Invoice&amp;action=CreatePDF4Mail&amp;return_module=Invoice
''' </summary>
''' <remarks></remarks>
Private Class UriWithCorrectDataEncoding
    Inherits Uri

    Public Sub New(url As String)
        MyBase.New(url)
    End Sub

    Public Overrides Function ToString() As String
        Return MyBase.AbsoluteUri
    End Function

End Class