讀寫檔案的另一個選擇 MemoryMappedFile

  • 2302
  • 0

使用 MemoryMappedFile 類別讀寫檔案

以往我們都是使用 System.IO.File 類別來撰寫關於檔案讀寫的程式,在 .Net Framework 4 以後的版本有另外一個選擇 -- MemoryMappedFile 類別。

不囉嗦,直接看程式碼吧。

    class FileProcessor
    {
        public static byte[] Read(string path)
        {
            byte[] result;
            using (var memoryMappedFile = MemoryMappedFile.CreateFromFile(path, FileMode.Open))
            {
                using (var memoryMappedViewStream = memoryMappedFile.CreateViewStream())
                {
                    result = new byte[memoryMappedViewStream.Length];
                    memoryMappedViewStream.Read(result, 0, result.Length);
                }
            }
            return result;
        }

        public static void Write(string path,byte[] content)
        {
            using (var memoryMappedFile = MemoryMappedFile.CreateFromFile(path, FileMode.Create, "save", content.Length))
            {
                using (var memoryMappedViewStream = memoryMappedFile.CreateViewStream())
                {
                    memoryMappedViewStream.Write(content, 0, content.Length);
                }
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
           var bytes = FileProcessor.Read("MilkyWay.jpg");

            FileProcessor.Write("MilkyWay002.jpg",bytes );
        }
    }

source code : https://github.com/billchungiii/MemoryMappedFileSample