将数据追加到字节数组 [英] Append Data to Byte Array

查看:180
本文介绍了将数据追加到字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我从一个二进制文件(File.ReadAllBytes)读取数据,此字节数组转换成字符串,并追加数据到这个字符串。 。最后,我转换字符串回一个字节数组,写入数据返回到一个新文件

Currently, I am reading data from a binary file (File.ReadAllBytes), converting this byte array into a string and appending data onto this string. Lastly, I am converting the string back into a byte array and writing the data back into a new file.

呀 - 这种方法是相当愚蠢的,我一直在好奇,是否有一些方法来此的新的的数据追加到字节数组(以字节的形式)的结束。

Yeah - this method is fairly idiotic, and I've been curious as to whether or not there is some way to append this new data onto the end of the byte array (in the form of a byte).

String s = @"C:\File.exe";
Byte b[] = File.ReadAllBytes(s);

String NewString = ConvertToString(b[]);

NewString = NewString + "Some Data";

b[] = ConvertToByteArray(NewString);
File.WriteAllBytes(b[]);



// ConvertToByteArray和ConvertToString表示转换字符串>字节>字符串函数。

// ConvertToByteArray and ConvertToString represent functions that converts string > Byte > string.

我想这样做的:

b[] = file.readallbytes(s)
b = b + "new Data"
file.writeallbytes(b[])



< 。p>非常感谢您对此事的见解。

Thank you very much for any insight on the matter.

推荐答案

您应该习惯用流的工作 - 在这种情况下,你可以使用的MemoryStream 来达到同样的事情没有那些讨厌的数组。

You should get used to working with Streams - in this case you could use a MemoryStream to achieve the exact same thing without all those nasty arrays.

byte[] bytes = File.ReadAllBytes(inFilePath);
using (MemoryStream ms = new MemoryStream())
{
    // You could also just use StreamWriter to do "writer.Write(bytes)"
    ms.Write(bytes, 0, bytes.Length);

    using (StreamWriter writer = new StreamWriter(ms))
    {
        writer.Write("Some Data");
    }

    File.WriteAllBytes(outFilePath, ms.ToArray());
}



Admitedly这看起来整个负载比你的代码更复杂,但在幕后它在做什么是更有效的。

Admitedly this looks a whole load more complicated than your code, but under the covers what it's doing is more efficient.

当然,如果你只是写到另一个文件(甚至是同一文件),你可以简单地直接写入到文件,并跳过需要一个字节阵列或的MemoryStream 完全 - 这是流的美

Of course if you are just writing to another file (or even the same file) you can simply write directly to the file and skip the need for a byte array or MemoryStream entirely - this is the beauty of streams.

这篇关于将数据追加到字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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