猿问

C# 将数据文件读入字节数组

我正在尝试将包含 16 位数字的大型数据文件读取到多维数组中,但我不确定 C# 中最快的方法。我还需要它来处理 8 位数字。在 C++ 中,我使用 fread() ,它非常快,并将数据读取到“myArray[,,,,]”中,然后可以将其作为多维数组进行访问:


numberRead = fread( myArray, sizeof(short), 19531250, stream );

在 C# 中,我可以使用循环,但这非常慢。


using (BinaryReader reader = new BinaryReader(File.OpenRead(filepath)))

{

  for (int i = 0; i < 25; i++)

    for (int j = 0; j < 25; j++)

      for (int k = 0; k < 25; k++)

        for (int m = 0; m < 25; m++)

          for (int n = 0; n < 25; n++)

          {

            myArray[i, j, k, m, n] = reader.ReadInt16();

          }

}

有没有更快的方法将文件读入可适应 8 位和 16 位数据的数组?


墨色风雨
浏览 78回答 1
1回答

烙印99

它很慢,因为您不断向文件系统请求小块数据。你最好先一次性将整个文件读入内存😉using (var memStream = new MemoryStream(File.ReadAllBytes(filepath)))using (BinaryReader reader = new BinaryReader(memStream)){&nbsp; &nbsp; for (int i = 0; i < 25; i++)&nbsp; &nbsp; &nbsp; &nbsp; for (int j = 0; j < 25; j++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int k = 0; k < 25; k++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int m = 0; m < 25; m++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int n = 0; n < 25; n++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; myArray[i, j, k, m, n] = reader.ReadInt16();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }}要读取有符号 8 位整数,请替换reader.ReadInt16()为reader.ReadSByte();
随时随地看视频慕课网APP
我要回答