字符串到字节的运行时错误 [英] String to byte Run Time Error

查看:68
本文介绍了字符串到字节的运行时错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,最近我注意到FromBase64String导致错误.
我该怎么办才能解决这个问题?

Hello, newly i notice that FromBase64String cause error.
what should i do to solve this?

string s = "Hello, World!";
byte[] plainText = Convert.FromBase64String(s);





报价:

Base-64字符串中的无效字符.

Invalid character in a Base-64 string.



请使用改善问题而不是提交解决方案-E.H.
OP奇迹:
那么我应该使用什么代替base64:-/来将我的字符串转换为字节并传递给加密算法?

我看到情况必须有字节,而不是字符串,这是我的问题:|



Please use Improve question instead of submit solution -- E.H.
OP wonders:
then what should i use instead of base64 :-/ to convert my string to byte and pass to encryption algorithm?

i see must cases have get byte, but not to string, that''s my problem :|

推荐答案

不要在想要的字符串中放入无效字符从Base64转换!
Base64包含大写和小写字母A-Z,0-9,仅加号"和斜杠".
其他任何字符都将导致错误.
Don''t put invalid characters in strings that you want to convert from Base64!
Base64 contains upper and lower case A-Z, 0-9, "plus" and "slash" only.
Any other characters will cause an error.


我在Google上搜索了"C#字符串到字节数组".
第一页上的第五项- http://www.dotnetperls.com/convert-string-byte-array [ ^ ]

我摆弄了一些东西,使这段代码可以工作:

I did a google search on "c# string to byte array".
Fifth item on first page - http://www.dotnetperls.com/convert-string-byte-array[^]

I fiddled around with things a bit and got this code to work:

// Input string.
const string input = "Hello, World!";

// Invoke GetBytes method.
// ... You can store this array as a field!
byte[] array = Encoding.ASCII.GetBytes(input);

// Loop through contents of the array.
foreach (byte element in array)
{
  System.Diagnostics.Debug.WriteLine((char)element);
}


摘自手册:

From the manual:

FormatException:

The length of s, ignoring white-space characters, is not zero or a multiple of 4.
-or-
The format of s is invalid. s contains a non-base-64 character, more than two padding characters, or a non-white space-character among the padding characters.



这意味着您的字符串长度也需要为4的倍数-我刚刚亲自测试过此字符串...



This means your string''s length also needs to a multiple of 4 - I have just tested this myself...


这篇关于字符串到字节的运行时错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆