H,
如何从C#中的.dat文件中读取前512个字节的数据?
我的dat文件包含二进制数据。
我目前正在使用File.ReadAllBytes
从dat文件中读取数据。但是它读取所有数据,我想只读取前512个字节然后中断。
我需要为这个或任何其他方法使用for循环。
任何帮助表示赞赏。
答案 0 :(得分:5)
你可以试试这个:
byte[] buffer = new byte[512];
try
{
using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
fs.Read(buffer, 0, buffer.Length);
fs.Close();
}
}
catch (System.UnauthorizedAccessException ex)
{
Debug.Print(ex.Message);
}
答案 1 :(得分:4)
您可以使用byte[]
变量和FileStream.Read。
答案 2 :(得分:0)
我相信最简单,最有效的方法是:
using (BinaryReader br = new BinaryReader(File.OpenRead(openFileDailog1.FileName)))
{
br.BaseStream.Seek(0x4D, SeekOrigin.Begin); //Put the beginning of a .dat file here. I put 0x4D, because it's the generic start of a file.
gameCode = Encoding.UTF8.GetString(br.ReadBytes(512)); //Or whatever string you want
}
br.Close();
希望这会有所帮助!