創建流,控制檯實現
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Threading;
namespace MemoryMapped
{
class Program
{
static void Main(string[] args)
{
string mapName = "mapTest";
long capacity = 104857600;
string path = @"C:\Users\Administrator\Desktop\map.txt";
if (!File.Exists(path))
{
Console.WriteLine("未查找到文件: " + path);
}
else
{
#region 文件傳輸
MemoryMappedFile memory = MemoryMappedFile.CreateOrOpen(mapName, capacity, MemoryMappedFileAccess.ReadWrite);
MemoryMappedViewAccessor viewAccessor = memory.CreateViewAccessor(0, capacity);
FileStream file = new FileStream(path, FileMode.Open);
long _length = file.Length;
byte[] data = new byte[_length];
Console.WriteLine("_length:" + _length);
file.Read(data, 0, data.Length);
file.Close();
viewAccessor.Write(0, data.Length);
viewAccessor.WriteArray<byte>(4, data, 0, data.Length);
Console.ReadLine();
#endregion
}
}
}
}
接收流,unity實現
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.MemoryMappedFiles;
using UnityEngine;
public class MemoryMapped : MonoBehaviour {
public string mapName = "mapTest";
MemoryMappedFile mappedFile;
MemoryMappedViewAccessor viewAccessor;
void Start ()
{
_MemoryMapped();
}
void _MemoryMapped()
{
long _long = 104857600; //傳輸的限制大小
string path = @"C:\Users\Administrator\Desktop\NewMap.txt"; //接收到的文件保存路徑
try
{
mappedFile = MemoryMappedFile.OpenExisting(mapName); //搜索指定的內存流
}
catch (System.Exception ex)
{
Debug.LogError("[MemoryMappedFile.OpenExisting] :" + ex.Message);
}
viewAccessor = mappedFile.CreateViewAccessor(0, _long); //創建流接收器
int strLength = viewAccessor.ReadInt32(0);
byte[] charsInMMf = new byte[strLength];
viewAccessor.ReadArray<byte>(4, charsInMMf, 0, strLength);
Debug.Log(charsInMMf.Length);
FileStream stream = new FileStream(path, FileMode.Create); //保存至路徑path
stream.Write(charsInMMf, 0, strLength);
stream.Close();
}
}