Search code examples
c#asp.netvisual-studio-2010filememory-mapped-files

How to read and write a file using Memory Mapped File C#?


I have an image in D Drive like "D:\Image\1.tiff". I want to read this file and write it in an another location, for example in the path "D:\Project\". How to do this using Memory Mapped File?


Solution

  • I can now achieve reading and writing a file using Memory Mapped File using the below coding:

    FileStream stream = File.OpenRead(@"D:\FFv1\dpx1\1.dpx");
    byte[] fileBytes = new byte[stream.Length];
    string Output = @"D:\Vanthiya Thevan\FFv1\dpx1\2.dpx";
    using (var fileStream = new FileStream(Output, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
    using (MemoryMappedFile memoryMapped = MemoryMappedFile.CreateFromFile(fileStream, "MapName", fileBytes.Length,
    MemoryMappedFileAccess.ReadWrite, new MemoryMappedFileSecurity(), HandleInheritability.Inheritable, true))
    {
        var viewStream = memoryMapped.CreateViewStream();
        viewStream.Write(fileBytes, 0, fileBytes.Length); 
    }