【问题标题】:How to read file binary in C#?如何在 C# 中读取文件二进制文件?
【发布时间】:2011-01-26 10:32:57
【问题描述】:

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

【问题讨论】:

  • 您的问题不清楚。这两个文件究竟应该是什么样子?
  • 我认为他想将文件的位模式存储到文本文件中。
  • 源文件是二进制还是编码(文本,ASCII、UTF-8、UTF-16 等)?换句话说,如果您在记事本等文本编辑器中打开文件,您会看到零和一吗?

标签: c# binary


【解决方案1】:

又快又脏的版本:

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

【讨论】:

  • @Andrey:见“又快又脏”。显然,在生产中,使用文件流的东西会好得多。重要的部分是将字节转换为二进制字符串。
【解决方案2】:

好吧,阅读它并不难,只需使用 FileStream 读取一个字节[]。除非您将 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();
    }
}

【讨论】:

  • 感谢您的回答。嗯..有些东西似乎不起作用,因为我没有得到 0 和 1。相反,我得到的效果就像我选择在记事本中打开文件一样。
  • 是的,它们是用十六进制编码的。与您在记事本中看到的不同。背景:en.wikipedia.org/wiki/Hexadecimal
  • 这个方法读取文件,能否提供一种方法,将二进制写入文件或将二进制数据写入文件,然后转换为十六进制读取回你这里的方式?跨度>
【解决方案3】:

您可以使用BinaryReader 读取每个字节,然后使用BitConverter.ToString(byte[]) 找出每个字节在二进制中的表示方式。

然后您可以使用此表示并将write 写入文件。

【讨论】:

    【解决方案4】:
    using (FileStream fs = File.OpenRead(binarySourceFile.Path))
        using (BinaryReader reader = new BinaryReader(fs))
        {              
            // Read in all pairs.
            while (reader.BaseStream.Position != reader.BaseStream.Length)
            {
                Item item = new Item();
                item.UniqueId = reader.ReadString();
                item.StringUnique = reader.ReadString();
                result.Add(item);
            }
        }
        return result;  
    

    【讨论】:

      【解决方案5】:

      使用简单的FileStream.Read 然后用Convert.ToString(b, 2) 打印出来

      【讨论】:

        【解决方案6】:

        一般来说,我真的看不出有什么可行的方法来做到这一点。我已经用尽了早期 cmets 给你的所有选项,但它们似乎不起作用。你可以试试这个:

                `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(object sender, 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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-02-17
          • 2017-10-01
          • 2011-09-03
          • 2016-01-15
          • 1970-01-01
          • 2016-01-20
          相关资源
          最近更新 更多