You haven’t said what error you’re getting, but surely your second code should simply be:
return Encoding.UTF8.GetString(Convert.FromBase64String(data));
- You don’t need to create a new
UTF8Encoding
- You don’t need to worry about decoders explicitly
Additionally, your exception handling is nasty – the stack trace would already show where the error occurs, but by catching it and rethrowing just Exception
you’re hiding the original exception type. Just remove the try/catch blocks from both your methods. (And rename them to match .NET naming conventions.)
Basically, your code can look as simple as this:
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));
}
Obviously you can split it into separate statements if you want, but it can stil be pretty short:
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);
}
0
solved Help me, throwing exception error in decoding code. help needed