本篇文章给大家分享的是有关怎么在c#中通过内存映射共享文件,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
using System;
using System.Collections.Generic;android从资源文件中读取文件流显示
using System.Linq;
using System.Text;
using System.IO;
//引用内存映射文件命名空间
using System.IO.MemoryMappedFiles;
namespace App1
{
class Program
{
static void Main(string[] args)
{
long capacity = 1<<10<<10;
//创建或者打开共享内存
using (var mmf = MemoryMappedFile.CreateOrOpen("testMmf", capacity, MemoryMappedFileAccess.ReadWrite))
{
//通过MemoryMappedFile的CreateViewAccssor方法获得共享内存的访问器
var viewAccessor = mmf.CreateViewAccessor(0, capacity);
//循环写入,使在这个进程中可以向共享内存中写入不同的字符串值
while (true)
{
Console.WriteLine("请输入一行要写入共享内存的文字:");
string input = Console.ReadLine();
//向共享内存开始位置写入字符串的长度
viewAccessor.Write(0, input.Length);
//向共享内存4位置写入字符
viewAccessor.WriteArray<char>(4, input.ToArray(), 0, input.Length);
}
}
}
}
}
App2代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
//引用使用内存映射文件需要的命名空间
using System.IO.MemoryMappedFiles;
namespace App2
{
class Program
{
static void Main(string[] args)
{
long capacity = 1<<10<<10;
using (var mmf = MemoryMappedFile.OpenExisting("testMmf"))
{
MemoryMappedViewAccessor viewAccessor = mmf.CreateViewAccessor(0, capacity);
//循环刷新共享内存字符串的值
while (true)
{
//读取字符长度
int strLength = viewAccessor.ReadInt32(0);
char[] charsInMMf = new char[strLength];
//读取字符
viewAccessor.ReadArray<char>(4, charsInMMf, 0, strLength);
Console.Clear();
Console.Write(charsInMMf);
Console.Write("\r");
Thread.Sleep(200);
}
}
}
}
}
App3代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.MemoryMappedFiles;
using System.IO;
namespace App3
{
class Program
{
static void Main(string[] args)
{
long capacity = 1 << 10 << 10;
//打开共享内存
using (var mmf = MemoryMappedFile.OpenExisting("testMmf"))
{
//使用CreateViewStream方法返回stream实例
using (var mmViewStream = mmf.CreateViewStream(0, capacity))
{
//这里要制定Unicode编码否则会出问题
using (BinaryReader rdr = new BinaryReader(mmViewStream,Encoding.Unicode))
{
while (true)
{
mmViewStream.Seek(0, SeekOrigin.Begin);
int length = rdr.ReadInt32();
char[] chars = rdr.ReadChars(length);
Console.Write(chars);
Console.Write("\r");
System.Threading.Thread.Sleep(200);
Console.Clear();
}
}
}
}
}
}
}
以上就是怎么在c#中通过内存映射共享文件,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。