开发者

Encode and Decode in c# asp.net?

开发者 https://www.devze.com 2023-03-31 03:26 出处:网络
i am using Encoding and decoding : For Encoding: private string EncodeServerName(string ServerName) { byte[] NameEncodein = new byte[ServerName.Length];

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 decod开发者_高级运维e 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


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));
}


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,....

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号