0

对于我的项目,我需要从文件中编写 UInt16、UInt32、字节和字符串。我从一个这样写的简单类开始:

    public FileReader(string path)  //constructor
    {
        if (!System.IO.File.Exists(path))
            throw new Exception("FileReader::File not found.");

        m_byteFile = System.IO.File.ReadAllBytes(path);
        m_readPos = 0;
    }
    public UInt16 getU16()   // basic function for reading
    {
        if (m_readPos + 1 >= m_byteFile.Length)
            return 0;

        UInt16 ret = (UInt16)((m_byteFile[m_readPos + 0])
                            + (m_byteFile[m_readPos + 1] << 8));
        m_readPos += 2;
        return ret;
    }

我认为使用已经存在的 BinaryReader 可能会更好,所以我尝试了它,但我注意到它比我的方法慢。有人可以解释为什么会这样吗?如果有另一个已经存在的类我可以用来加载文件并从中读取?

~阿杜拉

4

1 回答 1

1

您将所有数据预先存储在内存中的一个数组中,而BinaryReader一次从一个源流中传输一个字节,我猜这是磁盘上的一个文件。我想你可以通过传递一个从内存数组中读取的流来加速它:

Stream stream = new MemoryStream(byteArray);
//Pass the stream to BinaryReader

请注意,使用这种方法,您需要一次将整个文件填充到内存中,但我想这对您来说没问题。

于 2013-06-18T12:54:57.603 回答