如何在C#中读取文件二进制文件?

时间:2010-03-11 15:27:40

标签: c# binary

我想制作一个接收任何文件的方法,并将其作为0和1的数组读取,即其二进制代码。我想将该二进制代码保存为文本文件。你能帮助我吗?谢谢。

6 个答案:

答案 0 :(得分:48)

快速而肮脏的版本:

byte[] fileBytes = File.ReadAllBytes(inputFilename);
StringBuilder sb = new StringBuilder();

foreach(byte b in fileBytes)
{
    sb.Append(Convert.ToString(b, 2).PadLeft(8, '0'));  
}

File.WriteAllText(outputFilename, sb.ToString());

答案 1 :(得分:16)

好吧,阅读它并不难,只需使用FileStream读取一个byte []。除非将1和0转换为十六进制,否则将其转换为文本通常不太可能或没有意义。使用BitConverter.ToString(byte [])重载很容易。您通常希望在每行中转储16或32个字节。您可以使用Encoding.ASCII.GetString()来尝试将字节转换为字符。执行此操作的示例程序:

using System;
using System.IO;
using System.Text;

class Program {
    static void Main(string[] args) {
        // Read the file into <bits>
        var fs = new FileStream(@"c:\temp\test.bin", FileMode.Open);
        var len = (int)fs.Length;
        var bits = new byte[len];
        fs.Read(bits, 0, len);
        // Dump 16 bytes per line
        for (int ix = 0; ix < len; ix += 16) {
            var cnt = Math.Min(16, len - ix);
            var line = new byte[cnt];
            Array.Copy(bits, ix, line, 0, cnt);
            // Write address + hex + ascii
            Console.Write("{0:X6}  ", ix);
            Console.Write(BitConverter.ToString(line));
            Console.Write("  ");
            // Convert non-ascii characters to .
            for (int jx = 0; jx < cnt; ++jx)
                if (line[jx] < 0x20 || line[jx] > 0x7f) line[jx] = (byte)'.';
            Console.WriteLine(Encoding.ASCII.GetString(line));
        }
        Console.ReadLine();
    }
}

答案 2 :(得分:5)

您可以使用BinaryReader读取每个字节,然后使用BitConverter.ToString(byte[])查找每个字节的表示形式。

然后,您可以将此表示形式和write用于文件。

答案 3 :(得分:4)

使用简单FileStream.Read,然后使用Convert.ToString(b, 2)

打印

答案 4 :(得分:4)

{{1}}

答案 5 :(得分:1)

通常,我真的看不出有这样做的可能方法。我已经用尽了前面的评论中给您的所有选项,但它们似乎没有用。您可以尝试以下方法:

        `private void button1_Click(object sender, EventArgs e)
    {
        Stream myStream = null;
        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        openFileDialog1.InitialDirectory = "This PC\\Documents";
        openFileDialog1.Filter = "All Files (*.*)|*.*";
        openFileDialog1.FilterIndex = 1;
        openFileDialog1.RestoreDirectory = true;
        openFileDialog1.Title = "Open a file with code";

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            string exeCode = string.Empty;
            using (BinaryReader br = new BinaryReader(File.OpenRead(openFileDialog1.FileName))) //Sets a new integer to the BinaryReader
            {
                br.BaseStream.Seek(0x4D, SeekOrigin.Begin); //The seek is starting from 0x4D
                exeCode = Encoding.UTF8.GetString(br.ReadBytes(1000000000)); //Reads as many bytes as it can from the beginning of the .exe file
            }
            using (BinaryReader br = new BinaryReader(File.OpenRead(openFileDialog1.FileName)))
                br.Close(); //Closes the BinaryReader. Without it, opening the file with any other command will result the error "This file is being used by another process".

            richTextBox1.Text = exeCode;
        }
    }`
  • 这是“打开...”按钮的代码,但这是“保存...”按钮的代码:

    `private void button2_Click(对象发送者,EventArgs e)     {         SaveFileDialog save = new SaveFileDialog();

        save.Filter = "All Files (*.*)|*.*";
        save.Title = "Save Your Changes";
        save.InitialDirectory = "This PC\\Documents";
        save.FilterIndex = 1;
    
        if (save.ShowDialog() == DialogResult.OK)
        {
    
            using (BinaryWriter bw = new BinaryWriter(File.OpenWrite(save.FileName))) //Sets a new integer to the BinaryReader
            {
                bw.BaseStream.Seek(0x4D, SeekOrigin.Begin); //The seek is starting from 0x4D
                bw.Write(richTextBox1.Text);
            }
        }
    }`
    
    • 这是保存按钮。这可以正常工作,但仅显示“!无法在DOS模式下运行!”。 -否则,如果您可以解决此问题,我不知道该怎么办。

    • My Site