UrlEncode through a console application?

后端 未结 12 1259
我寻月下人不归
我寻月下人不归 2020-12-15 02:16

Normally I would just use:

HttpContext.Current.Server.UrlEncode(\"url\");

But since this is a console application, HttpContext.Curren

12条回答
  •  被撕碎了的回忆
    2020-12-15 02:50

    I ran into this problem myself, and rather than add the System.Web assembly to my project, I wrote a class for encoding/decoding URLs (its pretty simple, and I've done some testing, but not a lot). I've included the source code below. Please: leave the comment at the top if you reuse this, don't blame me if it breaks, learn from the code.

    ''' 
    ''' URL encoding class.  Note: use at your own risk.
    ''' Written by: Ian Hopkins (http://www.lucidhelix.com)
    ''' Date: 2008-Dec-23
    ''' 
    Public Class UrlHelper
        Public Shared Function Encode(ByVal str As String) As String
            Dim charClass = String.Format("0-9a-zA-Z{0}", Regex.Escape("-_.!~*'()"))
            Dim pattern = String.Format("[^{0}]", charClass)
            Dim evaluator As New MatchEvaluator(AddressOf EncodeEvaluator)
    
            ' replace the encoded characters
            Return Regex.Replace(str, pattern, evaluator)
        End Function
    
        Private Shared Function EncodeEvaluator(ByVal match As Match) As String
        ' Replace the " "s with "+"s
            If (match.Value = " ") Then
                Return "+"
            End If
            Return String.Format("%{0:X2}", Convert.ToInt32(match.Value.Chars(0)))
        End Function
    
        Public Shared Function Decode(ByVal str As String) As String
            Dim evaluator As New MatchEvaluator(AddressOf DecodeEvaluator)
    
            ' Replace the "+"s with " "s
            str = str.Replace("+"c, " "c)
    
            ' Replace the encoded characters
            Return Regex.Replace(str, "%[0-9a-zA-Z][0-9a-zA-Z]", evaluator)
        End Function
    
        Private Shared Function DecodeEvaluator(ByVal match As Match) As String
            Return "" + Convert.ToChar(Integer.Parse(match.Value.Substring(1), System.Globalization.NumberStyles.HexNumber))
        End Function
    End Class
    

提交回复
热议问题