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

Bor*_*ris 30 c# binary

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

Chr*_*ett 52

快速而肮脏的版本:

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());
Run Code Online (Sandbox Code Playgroud)

  • @Andrey:见“又快又脏”。显然,在生产中,使用文件流的东西会好得多。重要的部分是从字节转换为二进制字符串。 (2认同)

Han*_*ant 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();
    }
}
Run Code Online (Sandbox Code Playgroud)


Ode*_*ded 6

您可以使用BinaryReader读取每个字节,然后使用BitConverter.ToString(byte [])来查找每个字节如何用二进制表示。

然后,您可以使用此表示形式并将其写入文件。


小智 6

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;  
Run Code Online (Sandbox Code Playgroud)


And*_*rey 5

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