Read memory mapped file or knowing its size to read it correctely

[亡魂溺海] 提交于 2019-12-04 05:31:35

问题


In this question,

Read all contents of memory mapped file or Memory Mapped View Accessor without knowing the size of it

there is a problem, the (int)stream.Length is not giving me the correct length, it rather gives the size of the internal buffer used! I need to refresh this question because it is very pressing.

The main question was:

I need something similar to ReadToEnd or ReadAllBytes to read all of the contents of the MemoryMappedFile using the MappedViewAccessor if I don't know the size of it, how can I do it?

I have searched for it, I have seen this question, but it is not the thing I am looking for:

How can I quickly read bytes from a memory mapped file in .NET?

The old answer was:

pub

public static ReadMMFAllBytes(string fileName)
{
    using (var mmf = MemoryMappedFile.OpenExisting(fileName))
    {
        using (var stream = mmf.CreateViewStream())
        {
            using (BinaryReader binReader = new BinaryReader(stream))
            {
                return binReader.ReadBytes((int)stream.Length));
            }
        }
    }
}

In this question:

Memory Mapped File Length

There is no exact answer of the exact question! the question is about something else than the title.


回答1:


The best approach is to send over a fixed-length header of sorts first, rather than just streaming raw bytes. This way the first blob you read is a consistent length and it gives you the info you need to read the variable-length remainder.

In the simplest case, your record could be as simple as having a length field written first, followed by the payload (your bytes). Depending on your needs, you can add data to the header like record type, version, etc.



来源:https://stackoverflow.com/questions/15229166/read-memory-mapped-file-or-knowing-its-size-to-read-it-correctely

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!