2011-08-19 146 views
-3
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); 
    } 
} 
+2

也许你可以更明确地解释你的问题是什么? –

+1

也许告诉我们你真的得到了什么错误? – Jamiec

+2

和以往一样,任何说错误发生的问题都应该说明错误是什么。 –

回答

3

你还没说你得到了什么错误,但肯定你的第二个代码应该仅仅是:

return Encoding.UTF8.GetString(Convert.FromBase64String(data)); 
  • 你并不需要创建一个新的UTF8Encoding
  • 你不需要明确地解码解码器

此外,你的异常处理是讨厌的 - 堆栈跟踪已经显示错误r发生,但通过捕获它并重新抛出只是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)); 
} 

很明显,你可以将其分割成单独的语句,如果你想要的,但它可以STIL相当短:

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

@Downvoter:关心评论? –