二进制文件字符串 [英] binary file to string

查看:186
本文介绍了二进制文件字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图读取二进制文件(例如一个可执行文件)到一个字符串,然后将它写回

i'm trying to read a binary file (for example an executable) into a string, then write it back

FileStream fs = new FileStream("C:\\tvin.exe", FileMode.Open);
BinaryReader br = new BinaryReader(fs);
byte[] bin = br.ReadBytes(Convert.ToInt32(fs.Length));
System.Text.Encoding enc = System.Text.Encoding.ASCII;
string myString = enc.GetString(bin);
fs.Close();
br.Close();
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] rebin = encoding.GetBytes(myString);
FileStream fs2 = new FileStream("C:\\tvout.exe", FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs2);
bw.Write(rebin);
fs2.Close();
bw.Close();

这不工作(结果正好有字节大小相同,但不能运行)

this does not work (the result has exactly the same size in bytes but can't run)

如果我做bw.Write(箱)的结果是好的,但我必须将它保存为一个字符串

if i do bw.Write(bin) the result is ok, but i must save it to a string

推荐答案

在字节解码成一个字符串,并重新编码它们放回字节,你失去的信息。 ASCII特别是自ASCII码这是一个非常糟糕的选择会引发出了许多关于信息的方式,但可能会丢失信息时,编码和解码,无论你编码的类型挑,所以你不是在正确的道路上

When you decode the bytes into a string, and re-encodes them back into bytes, you're losing information. ASCII in particular is a very bad choice for this since ASCII will throw out a lot of information on the way, but you risk losing information when encoding and decoding regardless of the type of Encoding you pick, so you're not on the right path.

您需要的是BaseXX例程之一,二进制数据编码为可打印字符,通常用于存储或传输通过一个介质,只允许文本(电子邮件和新闻组浮现在脑海。)

What you need is one of the BaseXX routines, that encodes binary data to printable characters, typically for storage or transmission over a medium that only allows text (email and usenet comes to mind.)

ASCII85 是这样的一个算法,并在页面包含指向不同的实现。它具有4:1的比例:(规模增加了25%)5的含义,4个字节将被编码为5个字符

Ascii85 is one such algorithm, and the page contains links to different implementations. It has a ratio of 4:5 meaning that 4 bytes will be encoded as 5 characters (a 25% increase in size.)

如果不出意外,不过已经有了< A HREF =htt​​p://en.wikipedia.org/wiki/Base64> Base64的编码例行内置到.NET。它具有比例为3:4(以规模增长了33%),在这里:

If nothing else, there's already a Base64 encoding routine built into .NET. It has a ratio of 3:4 (a 33% increase in size), here:

  • Convert.ToBase64String Method
  • Convert.FromBase64String Method

下面是你的代码看起来像这些方法:

Here's what your code can look like with these methods:

string myString;
using (FileStream fs = new FileStream("C:\\tvin.exe", FileMode.Open))
using (BinaryReader br = new BinaryReader(fs))
{
    byte[] bin = br.ReadBytes(Convert.ToInt32(fs.Length));
    myString = Convert.ToBase64String(bin);
}

byte[] rebin = Convert.FromBase64String(myString);
using (FileStream fs2 = new FileStream("C:\\tvout.exe", FileMode.Create))
using (BinaryWriter bw = new BinaryWriter(fs2))
    bw.Write(rebin);

这篇关于二进制文件字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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