Подтвердить что ты не робот

Как читать двоичный файл в С#?

Я хочу сделать метод, который принимает любой файл и читает его как массив из 0 и 1, т.е. его двоичный код. Я хочу сохранить этот двоичный код в виде текстового файла. Вы можете мне помочь? Благодарю.

4b9b3361

Ответ 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());

Ответ 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();
    }
}

Ответ 3

Вы можете использовать BinaryReader для чтения каждого байта, а затем использовать BitConverter.ToString(byte []), чтобы узнать, как каждый представлен в двоичном виде.

Затем вы можете использовать это представление и записать его в файл.

Ответ 4

Используйте простой FileStream.Read, затем распечатайте его с помощью Convert.ToString(b, 2)

Ответ 5

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;  

Ответ 6

Вообще, я действительно не вижу возможного способа сделать это. Я исчерпал все варианты, которые дали вам предыдущие комментарии, и они, похоже, не работают. Вы можете попробовать это:

        '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!" - В противном случае, если вы можете это исправить, я не знаю, что делать.

    • Мой сайт