二进制文件转换为字符串

9
我正在尝试将二进制文件(例如可执行文件)读入字符串,然后将其写回。
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();

这个方法不起作用(结果的字节大小没有改变,但无法运行)

如果我使用bw.Write(bin),结果是正确的,但我必须将其保存到一个字符串中


进行十六进制比较,字节顺序是否相反?(从小端到大端) - Amirshk
为什么需要将其存储为字符串? - Lasse V. Karlsen
2个回答

22

将字节解码为字符串,然后重新将其编码回字节,您会丢失信息。特别是ASCII在这方面是一个非常糟糕的选择,因为ASCII将在途中丢失很多信息,但是无论您选择哪种编码类型,编码和解码时都有丢失信息的风险,因此您不是走上了正确的道路。

您需要的是其中一项BaseXX例程,用于将二进制数据编码为可打印字符,通常用于存储或传输到仅允许文本的介质(如电子邮件和新闻组)。

Ascii85 是这样一种算法,该页面包含对不同实现的链接。它具有4:5的比率,意味着4个字节将被编码为5个字符(大小增加25%)。

如果没有其他选择,.NET已经内置了Base64编码例程。它具有3:4的比率(大小增加33%),在此处:

使用这些方法,您的代码看起来像这样:

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

2

我认为你无法用ASCII来表示所有的字节。Base64是一种替代方法,但是它的字节和文本之间的比率为3:4。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接