Wednesday 9 May 2012

Beginning .Net , C# Tips : Reading contents of a MemoryMappedFile

Using streams does have a couple problems that might encounter in certain scenarios.
  1. When you open a file using a stream, reading the file contents is done sequentially. This can be a problem if you are searching for a specific section of a very large file because you have to read the entire file from the beginning in order to locate the content.
  2. Opening a file using a stream can lock the file, preventing other applications or threads from reading or writing to the file.

.NET Framework includes the System.IO.MemoryMappedFiles namespace, which includes a number of classes that allow you to create memory-mapped files. Memory-mapped files can be useful when you encounter the limitations of the stream objects.

Memory-mapped files allow to create views that start in a random location over very large files, rather than reading the file from the beginning. Memory-mapped files also allow multiple processes to map to the same portion of a file without locking the file.

C# Example :
byte[] bytes = new byte[100];
using (System.IO.MemoryMappedFiles.MemoryMappedFile objMF = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateFromFile(MapPath("TextFile.txt"), System.IO.FileMode.Open, "NewTextFile"))
{
    using (System.IO.MemoryMappedFiles.MemoryMappedViewAccessor accessor = objMF.CreateViewAccessor(100, 100))
    {
        accessor.ReadArray(0, bytes, 0, bytes.Length);
    }
}
Response.Write(ASCIIEncoding.Default.GetString(bytes));
This Example loads the TextFile.txt file into a MemoryMappedFile class using the static CreateFromFile method, which creates a named memory-mapped file. It then creates a MemoryMappedViewAccessor over the file using the MemoryMappedFiles CreateViewAccessor method. This method’s parameters allow  to specify an offset where the view accessor should start, the length of the view, and the access rights the view will have to the file.

The MemoryMappedFile class also allows to create memory-mapped files that are not associated with a physical file on disk, but are rather simply a named portion of memory. You can do this using the class’s static CreateNew method, which accepts a name and a length parameter.

VB.net Example :
Dim bytes As Byte() = New Byte(99) {}
    Using objMF As System.IO.MemoryMappedFiles.MemoryMappedFile = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateFromFile(MapPath("TextFile.txt"), System.IO.FileMode.Open, "NewTextFile")
        Using accessor As System.IO.MemoryMappedFiles.MemoryMappedViewAccessor = objMF.CreateViewAccessor(100, 100)
            accessor.ReadArray(0, bytes, 0, bytes.Length)
        End Using
    End Using
Response.Write(ASCIIEncoding.[Default].GetString(bytes))

2 comments:

  1. All your post are very interesting, shows essential info about various aspects of C#. Thanks!

    ReplyDelete
    Replies
    1. Hi Marek Wawrzynczyk,
      Thanks for your valuable comment.

      Delete