我想创建一个接收任何文件的方法,并将其作为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)
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)
小智 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)