Can we merge two memory mapped files?

怎甘沉沦 提交于 2019-12-08 09:12:41

问题


Can we merge two memory mapped files? if so the how? if not then why not?


回答1:


So here are my first experiences with MemoryMappedFiles, give it a try:

String f1Path = @"C:\Temp\Test1.txt";
String f2Path = @"C:\Temp\Test2.txt";
byte[] buffer;
int offset;
int length;

using (FileStream f1ReadStream = new FileStream(f1Path, FileMode.Open, FileAccess.Read))
{
    offset = (int)f1ReadStream.Length;
}
using (FileStream f2ReadStream = new FileStream(f2Path, FileMode.Open, FileAccess.Read))
{
    length = (int)f2ReadStream.Length;
}
// read file2 and append all to file1
using (var mappedFile2 = MemoryMappedFile.CreateFromFile(f2Path, FileMode.Open, null,  length))
{
    using (var reader = mappedFile2.CreateViewStream(0, length, MemoryMappedFileAccess.Read))
    {
        // Read from MMF
        buffer = new byte[length];
        reader.Read(buffer, 0, length);
    }
}

using (var mappedFile1 = MemoryMappedFile.CreateFromFile(f1Path,FileMode.Open, null, offset + length))
{
    // Create writer to MMF
    using (var writer = mappedFile1.CreateViewAccessor(offset, length, MemoryMappedFileAccess.Write))
    {
        // Write to MMF
        writer.WriteArray<byte>(0, buffer, 0, length);
    }
}


来源:https://stackoverflow.com/questions/9632338/can-we-merge-two-memory-mapped-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!