public HttpResponseMessage GetFile(string fileName)
        {
            if (!FileProvider.Exists(fileName))
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            long             fileLength = FileProvider.GetLength(fileName);
            var              fileInfo   = GetFileInfoFromRequest(this.Request, fileLength);
            var              mapName    = string.Format("FileDownloadMap_{0}", fileName);
            MemoryMappedFile mmf        = null;

            try
            {
                mmf = MemoryMappedFile.OpenExisting(mapName, MemoryMappedFileRights.Read);
            }
            catch (FileNotFoundException)
            {
                mmf = MemoryMappedFile.CreateFromFile(FileProvider.Open(fileName), mapName, fileLength,
                                                      MemoryMappedFileAccess.Read, null, HandleInheritability.None,
                                                      false);
            }
            using (mmf)
            {
                Stream stream
                    = fileInfo.IsPartial
                    ? mmf.CreateViewStream(fileInfo.From, fileInfo.Length, MemoryMappedFileAccess.Read)
                    : mmf.CreateViewStream(0, fileLength, MemoryMappedFileAccess.Read);

                var response = new HttpResponseMessage();
                response.Content = new StreamContent(stream);
                SetResponseHeaders(response, fileInfo, fileLength, fileName);
                return(response);
            }
        }
Пример #2
0
 protected override Boolean InitialiseInternal()
 {
     if (dumpToFile)
     {
         dataToDump = new List <RF1StructWrapper>();
     }
     lock (this)
     {
         if (!initialised)
         {
             try
             {
                 memoryMappedFile       = MemoryMappedFile.OpenExisting(rFactor1Constant.SharedMemoryName);
                 sharedmemorysize       = Marshal.SizeOf(typeof(rfShared));
                 sharedMemoryReadBuffer = new byte[sharedmemorysize];
                 initialised            = true;
                 Console.WriteLine("Initialised rFactor 1 shared memory");
             }
             catch (Exception)
             {
                 initialised = false;
             }
         }
         return(initialised);
     }
 }
Пример #3
0
        private string ReadIPCClassNameMMF()
        {
            MemoryMappedFile         mmf = null;
            MemoryMappedViewAccessor mma = null;

            try
            {
                byte[] buffer = new byte[128];
                mmf = MemoryMappedFile.OpenExisting("DS4Windows_IPCClassName.dat");
                mma = mmf.CreateViewAccessor(0, 128);
                mma.ReadArray(0, buffer, 0, buffer.Length);
                return(ASCIIEncoding.ASCII.GetString(buffer));
            }
            catch (Exception)
            {
                // Eat all exceptions
            }
            finally
            {
                if (mma != null)
                {
                    mma.Dispose();
                }
                if (mmf != null)
                {
                    mmf.Dispose();
                }
            }

            return(null);
        }
        public override void Release(int id)
        {
            Stream stream;

            if (_mapping.TryGetValue(id, out stream))
            {
                if (stream != null)
                {
                    stream.Dispose();
                }

                try
                {
                    var mappedFile = MemoryMappedFile.OpenExisting(GetMappedName(id));

                    if (mappedFile != null)
                    {
                        mappedFile.Dispose();
                    }
                }
                catch
                {
                }
            }
        }
Пример #5
0
        public void OpenCreatedFromFile(string name, MemoryMappedFileRights rights, HandleInheritability inheritability)
        {
            const int Capacity = 4096;

            using (TempFile file = new TempFile(GetTestFilePath()))
                using (FileStream fs = File.Open(file.Path, FileMode.Open))
                    using (MemoryMappedFile original = MemoryMappedFile.CreateFromFile(fs, name, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false))
                    {
                        using (MemoryMappedFile opened = MemoryMappedFile.OpenExisting(name))
                        {
                            Assert.Throws <IOException>(() => MemoryMappedFile.OpenExisting(name, MemoryMappedFileRights.AccessSystemSecurity));
                            Assert.Throws <IOException>(() => MemoryMappedFile.OpenExisting(name, MemoryMappedFileRights.AccessSystemSecurity, HandleInheritability.None));
                            ValidateMemoryMappedFile(opened, Capacity);
                        }
                        using (MemoryMappedFile opened = MemoryMappedFile.OpenExisting(name, rights | MemoryMappedFileRights.ReadPermissions))
                        {
                            ValidateMemoryMappedFile(opened, Capacity, RightsToAccess(rights));
                        }
                        using (MemoryMappedFile opened = MemoryMappedFile.OpenExisting(name, rights | MemoryMappedFileRights.ReadPermissions, inheritability))
                        {
                            ValidateMemoryMappedFile(opened, Capacity, RightsToAccess(rights), inheritability);
                        }
                    }

            // The map no longer exists
            Assert.Throws <FileNotFoundException>(() => MemoryMappedFile.OpenExisting(name));
            Assert.Throws <FileNotFoundException>(() => MemoryMappedFile.OpenExisting(name, MemoryMappedFileRights.Read));
            Assert.Throws <FileNotFoundException>(() => MemoryMappedFile.OpenExisting(name, MemoryMappedFileRights.Read, HandleInheritability.None));
        }
Пример #6
0
 /// <summary>
 /// Process B
 /// </summary>
 public void Read()
 {
     while (true)
     {
         try
         {
             using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("testmap"))
             {
                 Mutex mutex = Mutex.OpenExisting("testmapmutex");
                 Console.WriteLine("ProcessB waitone");
                 mutex.WaitOne();
                 using (MemoryMappedViewStream stream = mmf.CreateViewStream(0, 0))
                 {
                     BinaryReader bread = new BinaryReader(stream, Encoding.UTF8);
                     Console.WriteLine(bread.ReadString());
                 }
                 mutex.ReleaseMutex();
             }
         }
         catch (Exception e)
         {
             Console.WriteLine(e.Message);
         }
         finally
         {
             Thread.Sleep(10000);
         }
     }
 }
Пример #7
0
        /// <summary>
        ///  без создания файла на диске
        /// </summary>
        /// <param name="mmfFile"></param>
        /// <returns></returns>
        public object ReadObjectFromMemory(string mmfFile)
        {
            try
            {
                byte[] buffer;

                using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("sv"))
                {
                    // Create accessor to MMF
                    using (var accessor = mmf.CreateViewAccessor())
                    {
                        // Wait for the lock
                        Mutex mutex = Mutex.OpenExisting("MMF_IPC2");
                        mutex.WaitOne();

                        buffer = new byte[(int)accessor.Capacity];
                        // Read from MMF
                        accessor.ReadArray <byte>(0, buffer, 0, (int)accessor.Capacity);
                    }

                    return(ByteArrayToObject(buffer));
                }
            }
            catch (Exception ex) { MessageBox.Show("base read error " + mmfFile + ex.Message); }
            return(null);
        }
Пример #8
0
 /// <inheritdoc/>
 public bool Init(string game)
 {
     if (game.Equals(String.Empty))
     {
         // TODO check string game not empty
         // throw Exception
     }
     Game = game;
     try
     {
         _logger?.LogTrace(LoggingEvents.C2E_OPEN_CONNECTION, "Injector {0} Init", Game);
         mutex              = Mutex.OpenExisting(Game + "_mutex");
         memfile            = MemoryMappedFile.OpenExisting(Game + "_mem");
         memViewAccessor    = memfile.CreateViewAccessor();
         resultEventHandle  = EventWaitHandle.OpenExisting(Game + "_result");
         requestEventHandle = EventWaitHandle.OpenExisting(Game + "_request");
         _started           = true;
     }
     catch (System.Threading.WaitHandleCannotBeOpenedException ex)
     {
         _logger?.LogWarning(LoggingEvents.C2E_OPEN_CONNECTION, ex, "Shared Memory not created for: {0}", Game);
         _started = false;
     }
     finally
     {
         _logger?.LogTrace(LoggingEvents.C2E_OPEN_CONNECTION, "Injector {0} Init : {1}", Game, _started);
     }
     return(_started);
 }
        private bool ConnectToSharedMemory()
        {
            try
            {
                memoryStatus = AC_MEMORY_STATUS.CONNECTING;
                // Connect to shared memory
                physicsMMF    = MemoryMappedFile.OpenExisting("Local\\acpmf_physics");
                graphicsMMF   = MemoryMappedFile.OpenExisting("Local\\acpmf_graphics");
                staticInfoMMF = MemoryMappedFile.OpenExisting("Local\\acpmf_static");

                // Start the timers
                staticInfoTimer.Start();
                ProcessStaticInfo();

                graphicsTimer.Start();
                ProcessGraphics();

                physicsTimer.Start();
                ProcessPhysics();

                // Stop retry timer
                sharedMemoryRetryTimer.Stop();
                memoryStatus = AC_MEMORY_STATUS.CONNECTED;
                return(true);
            }
            catch (FileNotFoundException)
            {
                staticInfoTimer.Stop();
                graphicsTimer.Stop();
                physicsTimer.Stop();
                return(false);
            }
        }
Пример #10
0
 public bool Move(int dy)
 {
     if (Y + dy > 0 && Y + dy < MapSize[1] && Health > 0)
     {
         Mutex mutex = Mutex.OpenExisting("CollisionMutex");
         mutex.WaitOne();
         using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("RocketsMap"))
         {
             byte type = 1;
             using (MemoryMappedViewStream stream = mmf.CreateViewStream(X + MapSize[0] * Y, 0))
             {
                 BinaryReader writer = new BinaryReader(stream);
                 type = writer.ReadByte();
             }
             using (MemoryMappedViewStream stream = mmf.CreateViewStream(X + MapSize[0] * Y, 0))
             {
                 BinaryWriter writer = new BinaryWriter(stream);
                 writer.Write(0);
             }
             using (MemoryMappedViewStream stream = mmf.CreateViewStream(X + MapSize[0] * (Y + dy), 0))
             {
                 BinaryWriter writer = new BinaryWriter(stream);
                 writer.Write(type);
             }
         }
         mutex.ReleaseMutex();
         Y += dy;
         return(true);
     }
     else
     {
         return(false);
     }
 }
Пример #11
0
        private static void Run(string[] args)
        {
            using var mappedFile  = MemoryMappedFile.OpenExisting(args[0]);
            using var streamView  = mappedFile.CreateViewStream();
            using var pingWritten = Semaphore.OpenExisting(args[1]);
            using var pongWritten = Semaphore.OpenExisting(args[2]);

            numOfIters = Int32.Parse(args[3]);

            var buffer = new byte[256];

            for (int i = 0; i < numOfIters; ++i)
            {
                pingWritten.WaitOne();

                streamView.Seek(0, SeekOrigin.Begin);

                var bytesRead = streamView.Read(buffer, 0, 256);

                Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, bytesRead));

                streamView.Seek(0, SeekOrigin.Begin);
                streamView.Write(Encoding.ASCII.GetBytes(lineToSend));

                pongWritten.Release();
            }
        }
Пример #12
0
 private void readSM()
 {
     try
     {
         OFFSET = int.TryParse(txtOffset.Text, out OFFSET) ? OFFSET : 0;
         string mapName = $"Global\\{txtSuffix.Text}";
         using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting(mapName))
         {
             mutex.WaitOne();
             using (MemoryMappedViewStream stream = mmf.CreateViewStream())
             {
                 using (var br = new BinaryReader(stream))
                 {
                     newPLCWordData = new List <int>();
                     br.BaseStream.Seek(OFFSET, SeekOrigin.Begin);
                     while (br.BaseStream.Position < br.BaseStream.Length)
                     {
                         newPLCWordData.Add(br.ReadInt32());
                     }
                 }
             }
             mutex.ReleaseMutex();
         }
         lblLastReadTime.Text = DateTime.Now.ToString($"yyyy-MM-dd HH:mm:ss");
     }
     catch (FileNotFoundException)
     {
         MessageBox.Show(@"Memory-mapped file does not exist.");
         Console.WriteLine(@"Memory-mapped file does not exist.");
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Пример #13
0
        public static string Read(string mapName)
        {
            string output = string.Empty;

            try
            {
                using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting(mapName))
                {
                    using (MemoryMappedViewStream stream = mmf.CreateViewStream())
                    {
                        var    reader = new BinaryReader(stream);
                        string value  = reader.ReadString();
                        if (string.IsNullOrWhiteSpace(value))
                        {
                            // HARD-CODED constant
                            Tracer.Instance.TraceEvent(System.Diagnostics.TraceEventType.Verbose, 0, "Memory-mapped file is empty.");
                        }
                        else
                        {
                            // HARD-CODED constant
                            Tracer.Instance.TraceEvent(System.Diagnostics.TraceEventType.Verbose, 0, "Memory-mapped file requested.");
                            output = value;
                        }
                    }
                }
            }
            catch (FileNotFoundException)
            {
                // HARD-CODED constant
                Tracer.Instance.TraceEvent(System.Diagnostics.TraceEventType.Warning, 0, "Memory-mapped file does not exist.");
            }
            return(output);
        }
Пример #14
0
        public List <test> readOrders()
        {
            int size;

            size = Marshal.SizeOf(typeof(test));
            MemoryMappedFile sharedMemory = MemoryMappedFile.OpenExisting("MemoryFile111");
            test             t;
            List <test>      listOrder = new List <test>();

            using (MemoryMappedViewAccessor reader = sharedMemory.CreateViewAccessor(0, length, MemoryMappedFileAccess.Read))
            {
                for (long i = 0; i < length; i += size)
                {
                    reader.Read(i, out t);
                    unsafe
                    {
                        var res = t.getUnsafeString(t.tname).ToString();
                    }

                    if (t.name > 0)
                    {
                        listOrder.Add(t);
                    }
                    else
                    {
                        break;
                    }
                }
            }
            //переписать на редис
            return(listOrder);
        }
Пример #15
0
        private async void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            using (var sharedMemory = MemoryMappedFile.OpenExisting("SharedMemory"))
            {
                await Task.Run(() =>
                {
                    var latestMsg = string.Empty;
                    while (true)
                    {
                        using (var accessor = sharedMemory.CreateViewAccessor())
                        {
                            var size = accessor.ReadInt32(0);
                            var data = new char[size];
                            accessor.ReadArray <char>(sizeof(int), data, 0, data.Length);
                            var str = new string(data);
                            if (latestMsg != str)
                            {
                                latestMsg = str;
                                Dispatcher.Invoke(() => textBlock.Text += ("Data :" + str + "\r\n"));
                            }
                        }

                        Thread.Sleep(100);
                    }
                });
            }
        }
Пример #16
0
        public object ReadObjectFromMMF(string mmfFile)
        {
            Mutex mutex = null;

            try
            {
                // Get a handle to an existing memory mapped file
                MemoryMappedFile mmf = MemoryMappedFile.OpenExisting(mmfFile, MemoryMappedFileRights.Read);

                bool mutexCreated;
                mutex = new Mutex(true, "mmfMutex", out mutexCreated);
                mutex.WaitOne();
                // Create a view accessor from which to read the data
                MemoryMappedViewAccessor mmfReader = mmf.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read);

                // Create a data buffer and read entire MMF view into buffer
                byte[] buffer = new byte[mmfReader.Capacity];
                mmfReader.ReadArray <byte>(0, buffer, 0, buffer.Length);
                mutex.ReleaseMutex();
                // Convert the buffer to a .NET object
                return(ByteArrayToObject(buffer));
            }
            catch
            {
                try
                {
                    mutex.ReleaseMutex();
                }
                catch { }
                return((Object) new SleepAssistData());
            }
        }
Пример #17
0
        static void Main(string[] args)
        {
            uint unEventPermissions = 2031619; // Same as EVENT_ALL_ACCESS value in the Win32 realm

            IntPtr hEvent = IntPtr.Zero;

            hEvent = OpenEvent(unEventPermissions, false, "ClientReadOver");
            if (IntPtr.Zero == hEvent)
            {
                Console.WriteLine("OpenEvent: ClientReadOver failed! \n(press any key to continue.)");
                Console.ReadKey();
                return; // Exit
            }

            using (var mmf = MemoryMappedFile.OpenExisting("ShareMemoryTest"))
            {
                long capacity = 1 << 10 << 10;
                MemoryMappedViewAccessor viewAccessor = mmf.CreateViewAccessor(0, capacity);

                while (true)
                {
                    SetEvent(hEvent);                       //设置事件,但是如果不成功会怎样?
                    ProcessCommNoticeWarningInfo m_Info2;   //结构体

                    int offset = 8;                         //memcpy时候把信息都写到pmemcomm里面了.
                    viewAccessor.Read(offset, out m_Info2); // var type=viewAccessor.ReadInt32(offset); 逐个字段去读取
                    int    strLength = m_Info2.msglen;      //char[] message的长度
                    byte[] byteArray = new byte[strLength]; //c++的char不能对应c#的char, 只能用byte来处理
                    viewAccessor.ReadArray <byte>(offset + 16, byteArray, 0, strLength);
                    Console.WriteLine("type:{0},module:{1},warning_num:{2},msglen:{3}", m_Info2.type, m_Info2.module, m_Info2.warning_num, m_Info2.msglen);
                    Console.WriteLine(System.Text.Encoding.Default.GetString(byteArray));
                    Thread.Sleep(2500);
                }
            }
        }//end of mian
Пример #18
0
            public MemoryMappedInfo(string name, long size)
            {
                _name = name;
                _size = size;

                _memoryMappedFile = MemoryMappedFile.OpenExisting(_name);
            }
Пример #19
0
        public void Connect()
        {
            this.memoryMappedFile = MemoryMappedFile.OpenExisting(this.BUFFER_NAME);

            // NOTE: Make sure that BUFFER_SIZE matches the structure size in the plugin (debug mode prints that).
            this.fullSizeBuffer = new byte[this.BUFFER_SIZE_BYTES];
        }
 protected override Boolean InitialiseInternal()
 {
     if (dumpToFile)
     {
         dataToDump = new List <PCarsStructWrapper>();
     }
     lock (this)
     {
         if (!initialised)
         {
             try
             {
                 memoryMappedFile       = MemoryMappedFile.OpenExisting("$pcars$");
                 sharedmemorysize       = Marshal.SizeOf(typeof(pCarsAPIStruct));
                 sharedMemoryReadBuffer = new byte[sharedmemorysize];
                 initialised            = true;
                 Console.WriteLine("Initialised pcars shared memory");
             }
             catch (Exception)
             {
                 initialised = false;
             }
         }
         return(initialised);
     }
 }
Пример #21
0
    public AudioClip Load(string memory_name)
    {
        Debug.Log("CutEffectLoader.Load");

        // Open shared memory
        MemoryMappedFile         share_mem = MemoryMappedFile.OpenExisting(memory_name);
        MemoryMappedViewAccessor accessor  = share_mem.CreateViewAccessor();

        // Write data to shared memory
        int size = accessor.ReadInt32(0);

        byte[] data = new byte[size];
        accessor.ReadArray <byte>(sizeof(int), data, 0, data.Length);

        Debug.Log("DataSize = " + size);

        // Dispose resource
        accessor.Dispose();
        share_mem.Dispose();

        clip = WavUtility.ToAudioClip(data, 0, "wav");

        Debug.Log("clip = " + clip.loadState);

        return(clip);
    }
Пример #22
0
        /// <summary>
        /// 读取器同样用CreateViewStream创建了一个映射视图流,但这次需要读取权限。
        /// 现在可以使用StreamReader()方法从共享内存中读取内容
        /// </summary>
        /// <returns></returns>
        private static async Task ReaderUsingStreams()
        {
            try
            {
                Console.WriteLine("读取器(ReaderUsingStreams)");
                _mapCreated.Wait();
                Console.WriteLine("读取器开始(ReaderUsingStreams)");

                using (MemoryMappedFile mappedFile = MemoryMappedFile.OpenExisting(MAPNAME, MemoryMappedFileRights.Read))
                {
                    MemoryMappedViewStream stream = mappedFile.CreateViewStream(0, 10000, MemoryMappedFileAccess.Read);
                    using (var reader = new StreamReader(stream))
                    {
                        _dataWrittenEvent.Wait();
                        Console.WriteLine("现在可以开始读取(ReaderUsingStreams)");

                        for (int i = 0; i < 100; i++)
                        {
                            long   pos = stream.Position;
                            string s   = await reader.ReadLineAsync();

                            Console.WriteLine($"从位置{pos}上读取了{s}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Пример #23
0
        private bool ConnectToSharedMemory()
        {
            try
            {
                memoryStatus = AC_MEMORY_STATUS.CONNECTING;

                // Connect to shared memory
                physicsMMF    = MemoryMappedFile.OpenExisting("Local\\acpmf_physics");
                graphicsMMF   = MemoryMappedFile.OpenExisting("Local\\acpmf_graphics");
                staticInfoMMF = MemoryMappedFile.OpenExisting("Local\\acpmf_static");
                carsInfoMMF   = MemoryMappedFile.OpenExisting("Local\\acpmf_cars");

                physics    = ReadPhysics();
                graphics   = ReadGraphics();
                staticInfo = ReadStaticInfo();
                cars       = ReadCars();

                memoryStatus = AC_MEMORY_STATUS.CONNECTED;

                return(true);
            }
            catch (FileNotFoundException)
            {
                return(false);
            }
        }
Пример #24
0
        /// <summary>
        /// 读取器首先等待创建内存映射文件,再使用MemoryMappedFile.0penExisting打开它。
        /// 读取器只需要映射的读取权限。之后,与前面的写入器类似,创建一个视图访问器。
        /// 在读取数据之前,等待设置_dataWrittenEvent()读取类似于写入,
        /// 因为也要提供应该访问数据的位置,但是不同的Read方法,如Readlnt32,用于读取不同的数据类型
        /// </summary>
        private static void Reader()
        {
            try
            {
                Console.WriteLine("reader");
                _mapCreated.Wait();
                Console.WriteLine("reader开始");

                using (MemoryMappedFile mappedFile = MemoryMappedFile.OpenExisting(MAPNAME, MemoryMappedFileRights.Read))
                {
                    using (MemoryMappedViewAccessor accessor = mappedFile.CreateViewAccessor(0, 10000, MemoryMappedFileAccess.Read))
                    {
                        _dataWrittenEvent.Wait();
                        Console.WriteLine("现在可以开始读取");

                        for (int i = 0; i < 400; i += 4)
                        {
                            int result = accessor.ReadInt32(i);
                            Console.WriteLine($"从位置{i}上读取了{result}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Пример #25
0
        public void OpenCreatedNew(string mapName, MemoryMappedFileRights desiredAccessRights, HandleInheritability inheritability)
        {
            const int Capacity = 4096;

            using (MemoryMappedFile original = MemoryMappedFile.CreateNew(mapName, Capacity))
            {
                using (MemoryMappedFile opened = MemoryMappedFile.OpenExisting(mapName))
                {
                    Assert.Throws <IOException>(() => MemoryMappedFile.OpenExisting(mapName, MemoryMappedFileRights.AccessSystemSecurity));
                    Assert.Throws <IOException>(() => MemoryMappedFile.OpenExisting(mapName, MemoryMappedFileRights.AccessSystemSecurity, HandleInheritability.None));
                    ValidateMemoryMappedFile(opened, Capacity);
                }
                using (MemoryMappedFile opened = MemoryMappedFile.OpenExisting(mapName, desiredAccessRights | MemoryMappedFileRights.ReadPermissions)) // can't do anything if we don't have read permissions
                {
                    ValidateMemoryMappedFile(opened, Capacity, RightsToAccess(desiredAccessRights));
                }
                using (MemoryMappedFile opened = MemoryMappedFile.OpenExisting(mapName, desiredAccessRights | MemoryMappedFileRights.ReadPermissions, inheritability))
                {
                    ValidateMemoryMappedFile(opened, Capacity, RightsToAccess(desiredAccessRights), inheritability);
                }
            }

            // The map no longer exists
            Assert.Throws <FileNotFoundException>(() => MemoryMappedFile.OpenExisting(mapName));
            Assert.Throws <FileNotFoundException>(() => MemoryMappedFile.OpenExisting(mapName, MemoryMappedFileRights.ReadWrite));
            Assert.Throws <FileNotFoundException>(() => MemoryMappedFile.OpenExisting(mapName, MemoryMappedFileRights.ReadWrite, HandleInheritability.None));
        }
        public static void Test()
        {
            // 打开内存映射文件.
            using (var mmf = MemoryMappedFile.OpenExisting("TextA"))
            {
                using (var accessor = mmf.CreateViewAccessor(offset, length))
                {
                    for (long i = 0; i < length; i++)
                    {
                        // 数据读取.
                        byte dataChar = accessor.ReadByte(i);

                        // 输出.
                        Console.Write((char)dataChar);

                        // 数据写入.
                        accessor.Write(i, (byte)(dataChar - 1));
                    }
                }

                Console.WriteLine();
            }


            Console.WriteLine("程序修改了部分内存映射文件。");
        }
Пример #27
0
        private MemoryMappedFile CreateFileIfMissing(string dir, string fileName)
        {
            string filePath = Path.Combine(dir, fileName);

            if (!File.Exists(filePath))
            {
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
            }

            var mmfName          = CatConstants.ID_MARK_FILE_MAP + "-" + fileName;
            MemoryMappedFile mmf = null;

            try
            {
                mmf = MemoryMappedFile.OpenExisting(mmfName, MemoryMappedFileRights.ReadWrite, HandleInheritability.Inheritable);
            }
            catch (System.IO.FileNotFoundException)
            {
                var stream = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
                //  MemoryMappedFileSecurity security = new MemoryMappedFileSecurity();
                mmf = MemoryMappedFile.CreateFromFile(stream, mmfName, CatConstants.ID_MARK_FILE_SIZE,
                                                      MemoryMappedFileAccess.ReadWrite, HandleInheritability.Inheritable, false);
            }
            return(mmf);
        }
Пример #28
0
        //List<CVarHeader> VarHeaders = new List<CVarHeader>();

        public bool Startup()
        {
            if (IsInitialized)
            {
                return(true);
            }

            try
            {
                iRacingFile = MemoryMappedFile.OpenExisting(Defines.MemMapFileName);
                FileMapView = iRacingFile.CreateViewAccessor();

                VarHeaderSize = Marshal.SizeOf(typeof(VarHeader));

                var hEvent = OpenEvent(Defines.DesiredAccess, false, Defines.DataValidEventName);
                var are    = new AutoResetEvent(false);
                are.Handle = hEvent;

                var wh = new WaitHandle[1];
                wh[0] = are;

                WaitHandle.WaitAny(wh);

                Header = new CiRSDKHeader(FileMapView);
                GetVarHeaders();

                IsInitialized = true;
            }
            catch (Exception)
            {
                return(false);
            }
            return(true);
        }
Пример #29
0
        protected async void StartInternal(string pipeName, bool isServer)
        {
            currentPipeName = pipeName;
            readCts         = new CancellationTokenSource();
            if (isServer)
            {
                receiver = MemoryMappedFile.CreateOrOpen(pipeName + "_receiver", capacity);
                sender   = MemoryMappedFile.CreateOrOpen(pipeName + "_sender", capacity);
            }
            else
            {
                while (true)
                {
                    try
                    {
                        receiver = MemoryMappedFile.OpenExisting(pipeName + "_sender");   //サーバーと逆方向
                        sender   = MemoryMappedFile.OpenExisting(pipeName + "_receiver"); //サーバーと逆方向
                        break;
                    }
                    catch (System.IO.FileNotFoundException) { }
                    if (readCts.Token.IsCancellationRequested)
                    {
                        return;
                    }
                    await Task.Delay(100);
                }
            }
            receiverAccessor = receiver.CreateViewAccessor();
            senderAccessor   = sender.CreateViewAccessor();
            var t = Task.Run(() => ReadThread());

            IsConnected = true;
        }
Пример #30
0
        private static async Task MainAsync(string[] args)
        {
            var mmfName = args[0];

            Boot.Instance.Start(typeof(Program).Assembly);
            try
            {
                using (var mmf = MemoryMappedFile.OpenExisting(mmfName))
                {
                    string fileString;
                    using (var stream = mmf.CreateViewStream())
                    {
                        var reader = new BinaryReader(stream);
                        fileString = reader.ReadString();
                    }

                    _log.Debug($"File value: {fileString}");
                    using (var input = mmf.CreateViewStream())
                    {
                        var writer = new BinaryWriter(input);
                        writer.Write(mmfName);
                    }
                }
            }
            catch (Exception e)
            {
                _log.Error(e);
                _log.Error(e.Message);
                _log.Error(e.InnerException?.Message);
            }
        }