Is MemoryMappedFile.CreateNew(...) guaranteed to create a file with zeroes?

641 views Asked by At

As the title says; Can I rely on MemoryMappedFile to always create a file full of zeroes? I've tested by reading some newly created files but this "testing" seems futile, altough I have yet to see a non-zero byte.

Is there any documentation on this that I have missed, or is it simply a given that memory mapped files are empty on creation.

1

There are 1 answers

2
Cory Nelson On BEST ANSWER

No, this is not guaranteed. This appears to be implementation-specific.

While not mentioned in MemoryMappedFile, the behavior of the underlying native API that it uses in .NET proper (CreateFileMapping) does explicitly document this, and it differs depending on the source of the storage.

In the case of a file-backed mapping:

If the file is extended, the contents of the file between the old end of the file and the new end of the file are not guaranteed to be zero; the behavior is defined by the file system.

And in the case of an anonymous mapping (backed by page file):

The initial contents of the pages in a file mapping object backed by the operating system paging file are 0 (zero).