I know that I could use HttpServerUtility.UrlTokenDecode Method to do the job. But the problem is that I am using .NET 1.1 and this method is only supported in .NET 2.0+. Also I found that Convert开发者_开发百科.ToBase64String method is not an option because of the differences addressed here. So what other options do I have? Do I have to write my own converting method?
Thanks.
If UrlTokenDecode
will get the job done, why not use it? I know you are using .NET 1.1, but you can use Reflector to decompile the method from the 2.0 framework and then create your own version.
Here's the underlying code for that method. I've not tested it, but I imagine that if you add this as a method to a class in your project you should be off and running...
internal byte[] UrlTokenDecode(string input)
{
if (input == null)
{
throw new ArgumentNullException("input");
}
int length = input.Length;
if (length < 1)
{
return new byte[0];
}
int num2 = input[length - 1] - '0';
if ((num2 < 0) || (num2 > 10))
{
return null;
}
char[] inArray = new char[(length - 1) + num2];
for (int i = 0; i < (length - 1); i++)
{
char ch = input[i];
switch (ch)
{
case '-':
inArray[i] = '+';
break;
case '_':
inArray[i] = '/';
break;
default:
inArray[i] = ch;
break;
}
}
for (int j = length - 1; j < inArray.Length; j++)
{
inArray[j] = '=';
}
return Convert.FromBase64CharArray(inArray, 0, inArray.Length);
}
If as the title states, you need to encode rather than decode, then here's the Encode version of the method which I've tested and seems to work just fine.
public static string UrlTokenEncode(byte[] input)
{
if (input == null)
throw new ArgumentNullException("input");
if (input.Length < 1)
return string.Empty;
string str = Convert.ToBase64String(input);
if (str == null)
return (string)null;
int length = str.Length;
while (length > 0 && (int)str[length - 1] == 61)
--length;
char[] chArray = new char[length + 1];
chArray[length] = (char)(48 + str.Length - length);
for (int index = 0; index < length; ++index)
{
char ch = str[index];
switch (ch)
{
case '+':
chArray[index] = '-';
break;
case '/':
chArray[index] = '_';
break;
case '=':
chArray[index] = ch;
break;
default:
chArray[index] = ch;
break;
}
}
return new string(chArray);
}
精彩评论