To encode a string
Code:
public string base64Encode(string data)
{
try
{
byte[] encData_byte = new byte[data.Length];
encData_byte = System.Text.Encoding.UTF8.GetBytes(data);
string encodedData = Convert.ToBase64String(encData_byte);
return encodedData;
}
catch(Exception e)
{
throw new Exception("Error in base64Encode" + e.Message);
}
}
and to decode
Code:
public string base64Decode(string data)
{
try
{
System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
System.Text.Decoder utf8Decode = encoder.GetDecoder();
byte[] todecode_byte = Convert.FromBase64String(data);
int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
char[] decoded_char = new char[charCount];
utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
string result = new String(decoded_char);
return result;
}
catch(Exception e)
{
throw new Exception("Error in base64Decode" + e.Message);
}
}
答案 0 :(得分:3)
你还没有说出你得到的错误,但你的第二个代码肯定应该只是:
return Encoding.UTF8.GetString(Convert.FromBase64String(data));
UTF8Encoding
此外,您的异常处理是令人讨厌的 - 堆栈跟踪已经显示错误发生的位置,但通过捕获它并仅重新抛出Exception
,您将隐藏原始异常类型。只需从您的方法中删除try / catch块。 (并将它们重命名以匹配.NET命名约定。)
基本上,您的代码看起来很简单:
public static string Base64AndUtf8Encode(string text)
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(text));
}
public static string Base64AndUtf8Decode(string base64)
{
return Encoding.UTF8.GetString(Convert.FromBase64String(base64));
}
显然你可以根据需要将它拆分成单独的语句,但它可以很短:
public static string Base64AndUtf8Encode(string text)
{
byte[] bytes = Encoding.UTF8.GetBytes(text);
return Convert.ToBase64String(bytes);
}
public static string Base64AndUtf8Decode(string base64)
{
bytes[] bytes = Convert.FromBase64String(base64);
return Encoding.UTF8.GetString(bytes);
}