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

smq 2005-07-18 09:49:25
请问如何读取二进制文件,我用filestream读取的是一个byte数组,难道要将字节一个一个地转换为整形或浮点型吗?有没有直接从二进制文件中读取多个整形或浮点型数据的函数?
...全文
551 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
MauveDragon 2005-10-27
  • 打赏
  • 举报
回复
那么如何进行二进制文件的随机读写呢?
vrace 2005-07-18
  • 打赏
  • 举报
回复
用 BinaryReader

FileStream fs = new FileStream("xxx.bin", FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);

BinaryReader 的用法可以自己查一下 .NET Framework SDK 文档
smq 2005-07-18
  • 打赏
  • 举报
回复
我希望一次读出来多个整数或浮点数,就像C++中fread(dataPointer, sizeof(int), num, fp)一样,而不是每次只读取一个或每次通过字节转换一个数
gOODiDEA 2005-07-18
  • 打赏
  • 举报
回复
use binaryReader

eg:

FileStream fs = new FileStream( dataFilePath, FileMode.Open, FileAccess.Read, FileShare.Read );
BinaryReader br = new BinaryReader( fs );
width = br.ReadInt32();
height = br.ReadInt32();
dafeifei 2005-07-18
  • 打赏
  • 举报
回复
我记得在哪看过的
byte[] b;
int c;

c=b[0]+b[1]+b[2]+b[3]; 整型四个字节,不知道行不行

不过共用体的话肯定是可以的,推荐用这个
struct myunion
{
[FieldOffset(0)] int c;
[FieldOffset(0)] byte b0;
[FieldOffset(1)] byte b1;
[FieldOffset(2)] byte b2;
[FieldOffset(3)] byte b3;
}//大概就这个意思吧,具体你在VS中就可以试出来了
gOODiDEA 2005-07-18
  • 打赏
  • 举报
回复
sorry

int [,,] cellData = new int[ width, height ];
==>
int [,] cellData = new int[ width, height ];

cellData[z,i,j] = br.ReadInt32();
==>
cellData[i,j] = br.ReadInt32();

gOODiDEA 2005-07-18
  • 打赏
  • 举报
回复
binaryReader本身的效率很不错了,它可以直接读成int的,不需要从BitConverter去转换

FileStream fs = new FileStream( dataFilePath, FileMode.Open, FileAccess.Read, FileShare.Read );
BinaryReader br = new BinaryReader( fs );
width = br.ReadInt32();
height = br.ReadInt32();
int [,,] cellData = new int[ width, height ];
for ( int j = 0 ; j < width; j++ )
{
for ( int i = 0 ; i < height; i++ )
{
cellData[z,i,j] = br.ReadInt32();
}
}
smq 2005-07-18
  • 打赏
  • 举报
回复
BinaarReader 读取返回的是一个byte 的数组,怎样将他转换为整形数组啊?如下所示,效率太低了
Byte []pByte = new Byte[512];

FileStream fs = new FileStream("F:\\data\\SL.3D.GSHANG11", FileMode.Open, FileAccess.Read);

// Read data from Test.data.
for (int i = 0; i < 1; i++)
{
fs.Read(pByte, 0, 512);

for(int j = 0; j < 128; j++)
{
int mm = BitConverter.ToInt32(pByte, j*4);
}
}
fs.Close();

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧