Encode and Decode in c# asp.net?

匿名 (未验证) 提交于 2019-12-03 02:52:02

问题:

i am using Encoding and decoding :

For Encoding:

private string EncodeServerName(string ServerName)     {       byte[] NameEncodein = new byte[ServerName.Length];       NameEncodein = System.Text.Encoding.UTF8.GetBytes(ServerName);       string EcodedName = Convert.ToBase64String(NameEncodein);       return EcodedName;     } 

and Decoding:

     public string DecoAndGetServerName(string Servername)      {          System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();          System.Text.Decoder strDecoder = encoder.GetDecoder();          byte[] to_DecodeByte = Convert.FromBase64String(Servername);          int charCount = strDecoder.GetCharCount(to_DecodeByte, 0, to_DecodeByte.Length);          char[] decoded_char = new char[charCount];          strDecoder.GetChars(to_DecodeByte, 0, to_DecodeByte.Length, decoded_char,0);          string Name = new string(decoded_char);           return Name;      } 

I am sending ServerName:DEV-SQL1\SQL2008

It is encoded:REVWLVNRTDFcU1FMMjAwOA==

Again i want to decode but getting Exception:in line:

byte[] to_DecodeByte = Convert.FromBase64String(Servername);

Exception IS:

`The input is not a valid Base-64 string as it contains a non-base 64 character,

more than two padding characters, or a non-white space character among the padding characters.`

How to solve this issue.

Please Help Me

回答1:

Your code seems way too complex :-), here is one that works:

public static string EncodeServerName(string serverName) {     return Convert.ToBase64String(Encoding.UTF8.GetBytes(serverName)); }  public static string DecodeServerName(string encodedServername) {     return Encoding.UTF8.GetString(Convert.FromBase64String(encodedServername)); } 


回答2:

the same code works for me, which you written in DecoAndGetServerName().

the thing is, you need to pass ENCODED STRING to your DecoAndGetServerName() function,

which might be encoded like :

string Servername=Convert.ToBase64String(Encoding.UTF8.GetBytes("serverName")); 

That's why you got that Error The input is not a valid Base-64 string as it contains a non-base 64 character,....



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!