简体   繁体   English

在C#中创建二进制文件的正确方法

[英]The correct way to create Binary files in C#

I'm using the below code to create a Binary file. 我正在使用以下代码来创建Binary文件。

var a = new[]
{
    "C50-12-25",
    "C50-12-20"
};

using (var bw = new BinaryWriter(File.Open("file.bin", FileMode.Create)))
{
    foreach (var i in a)
    {
        bw.Write(i);
    }
}

I opened the file and I'm not seeing something that resembles a picture like this which I always thought a Binary file would look like. 我打开文件,我没有看到像这样的图片,我一直认为Binary文件看起来像。

http://www.dotnetperls.com/binary.png http://www.dotnetperls.com/binary.png

I'm actually able to read the complete text I have written. 我实际上能够阅读我写的全文。

C50-12-25   C50-12-20

So is this it? 这是这样吗? I'm completely new to this so any help to point me in correct direction will be a lot to me. 我对此完全陌生,所以任何指导我正确方向的帮助对我来说都是很重要的。

The overload of Write that you used: BinaryWriter.Write(String) , writes out the string you provided to the file using encoding. 您使用的Write重载: BinaryWriter.Write(String) ,使用编码写出您提供给文件的字符串。

It looks like you you want to convert those strings to binary data by decoding them as hexadecimal values... except they don't look like hexadecimal values because they don't come in groups of 2. Anyway, this procedure is documented here ( How can I convert a hex string to a byte array? ). 看起来你想通过将它们解码为十六进制值来将这些字符串转换为二进制数据...除了它们看起来不像十六进制值,因为它们不是2组。无论如何,这个过程记录在这里( 如何将十六进制字符串转换为字节数组? )。

Note that the "picture" you posted is of a hex editor. 请注意,您发布的“图片”是十六进制编辑器。 You didn't describe in your post how you opened the file; 您没有在帖子中描述如何打开文件; if you open a file in Notepad or a similar editor then you'll always get printed-characters back, not the hexadecimal representation of the file's contents. 如果您在记事本或类似的编辑器中打开文件,那么您将始终返回打印字符,而不是文件内容的十六进制表示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM