我试图用Visual Basic .net(v.2008)编写下一个用C#编写的API。 视觉基础应该怎么样?
private static string UrlEncode(string url)
{
StringBuilder encoded = new StringBuilder(url.Length * 2);
string unreservedChars = String.Concat(ValidUrlCharacters, ValidPathCharacters);
foreach (char symbol in System.Text.Encoding.UTF8.GetBytes(url))
{
if (unreservedChars.IndexOf(symbol) != -1)
{
encoded.Append(symbol);
}
else
{
encoded.Append("%").Append(string.Format(CultureInfo.InvariantCulture, "{0:X2}", (int)symbol));
}
}
return encoded.ToString();
}
我已经尝试了下一个代码,但它没有用。它不返回字符,并且在字符串unreservedChars中找不到它。
代码适用于C#。
Private Shared Function UrlEncode(ByVal url As String) As String
Dim encoded As New StringBuilder(url.Length * 2)
Dim unreservedChars As String = String.Concat(ValidUrlCharacters, ValidPathCharacters)
For Each Symbol As String In System.Text.Encoding.UTF8.GetBytes(url)
If unreservedChars.IndexOf(Symbol) <> -1 Then
encoded.Append(Symbol)
Else
encoded.Append("%").Append(String.Format(CultureInfo.InvariantCulture, "{0:X2}", CInt(Symbol)))
End If
Next
Return encoded.ToString()
End Function
答案 0 :(得分:3)
你应该完全摆脱它,并根据你真正想要的东西打电话给Uri.EscapeUriString
或Uri.EscapeDataString
。
答案 1 :(得分:1)
您的VB版本有两个问题 - 您使用'String'作为迭代变量而不是'Char',而不是'CInt',您应该使用'AscW'从'Char'转到'Integer':
Private Shared Function UrlEncode(ByVal url As String) As String
Dim encoded As New StringBuilder(url.Length * 2)
Dim unreservedChars As String = String.Concat(ValidUrlCharacters, ValidPathCharacters)
For Each bytesymbol As Byte In System.Text.Encoding.UTF8.GetBytes(url)
Dim symbol As Char = ChrW(bytesymbol)
If unreservedChars.IndexOf(symbol) <> -1 Then
encoded.Append(symbol)
Else
encoded.Append("%").Append(String.Format(CultureInfo.InvariantCulture, "{0:X2}", AscW(symbol)))
End If
Next bytesymbol
Return encoded.ToString()
End Function