1

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.

Community
  • 1
  • 1
Saw
  • 6,199
  • 11
  • 53
  • 104
  • Did this answer help? http://stackoverflow.com/a/8613300/2258 Or Jon Skeet's answer: http://stackoverflow.com/a/221941/2258 – Richard Morgan Mar 05 '13 at 16:46
  • Didn't work, it gives me 4096 bytes even if the file is empty:( – Saw Mar 05 '13 at 17:00
  • Just write the stream length as well, at the beginning of the view. – Hans Passant Mar 05 '13 at 19:16
  • I am failing to see a question here. Can you edit the question make it clear about exactly what you're asking? – Kev Mar 07 '13 at 16:11
  • Simply, I need to read the memory mapped file without a previous information about it's size, If I tried to read it as I read any other stream, it will be with a wrong size, it's size will be rounded to X4096 number (Or to the closest system page size). – Saw Mar 07 '13 at 17:26

1 Answers1

0

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.

Will Chesterfield
  • 1,780
  • 12
  • 15