开发者

c# Read Binary data onto a string

I have seen plenty of examples of how to convert 开发者_运维知识库a byte array into a string, but this is causing me many problems down the road when I start to work with encryption. Just out of curiosity, does anyone know of a method to read binary data straight onto a string.

The VB6 method of doing this would be:

Dim S as string
s = space$(lof(1))
Get #1,, s
close #1

If not, I have seen different ways of converting string to byte array, back to string including base64, UTF8, and lastly - going through char by char and converting it into a byte.

My goal is simple. I want to retrieve binary data onto a string, encrypt this string, and lastly write all of the strings data back into a new binary file.

Which method would you say is the fastest way of doing this?


If you simply want to encrypt binary data then you should avoid using a string altogether. If you are encrypting textual information that belongs in a string then you should be caring about encodings (UTF-8 and friends) - although reading in data, putting it into a string, encrypting the string and then writing out data seems an odd requirement.


You state that you want to go from byte[] to string to byte[]; firstly, note that Encoding (such as UTF-8) is not an option; that only applies when going string to binary back to string. The difference is important: it needs to actually be textual data for that to work, and an arbitrary byte[] can not be treated as textual data. This also rules out your "direct write into a string", for similar reasons (not limited to: surrogates etc).

The correct way to encode binary to a string is with base-64, base-16, etc; base-64 is the most efficient general purpose encoding here.

However; most encryption code works with binary, not text. If you have a text encryption API, in most cases the first thing it is going to do is to turn it into binary using an encoding such as UTF-8.

So: check you aren't missing a direct binary API option.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜