我想知道如何以二进制格式读取文件。
例如,tiff图像文件可以具有以下二进制格式(十六进制0000 4949 002A 0000)。 我怎样才能在c#中获得这些值?
答案 0 :(得分:3)
以下是我通常以十六进制格式读取文件的方法,根据需要更改标题:
using System;
using System.Linq;
using System.IO;
namespace FileToHex
{
class Program
{
static void Main(string[] args)
{
//read only 4 bytes from the file
const int HEADER_SIZE = 4;
byte[] bytesFile = new byte[HEADER_SIZE];
using (FileStream fs = File.OpenRead(@"C:\temp\FileToHex\ex.tiff"))
{
fs.Read(bytesFile, 0, HEADER_SIZE);
fs.Close();
}
string hex = BitConverter.ToString(bytesFile);
string[] header = hex.Split(new Char[] { '-' }).ToArray();
Console.WriteLine(System.String.Join("", header));
Console.ReadLine();
}
}
}
答案 1 :(得分:2)
您可以使用System.IO.File类的ReadAllBytes方法将字节读入数组:
System.IO.FileStream fs = new System.IO.FileStream(@"C:\Temp\sample.pdf", System.IO.FileMode.Open, System.IO.FileAccess.Read);
int size = 1024;
byte[] b = new byte[size];
fs.Read(b, 0, size);
答案 2 :(得分:0)
我没有使用过LibTIFF.Net,http://bitmiracle.com/libtiff但似乎相当完整。
使用它,而不是将文件作为字节读取然后解码标题可能会更容易。