使用MemoryManagedViewAccessor将json序列化字符串写入文件

时间:2018-05-21 19:33:36

标签: c# file memory-mapped-files

我是MemoryMappedFiles的新手。我正在使用MemoryMappedFile创建一个文件,我想写一个json字符串。但问题是MemoryMappedViewAccessor的Write方法没有任何重载接收字符串。请帮忙。

 class ApplicationSettingsViewModel
        {
            ApplicationSettingsModel model;
            MemoryMappedFile mmf = null;
            //This is not a singleton class but I guess it has to be one but its ok for demonstration.
            public ApplicationSettingsViewModel()
            {
                model = new ApplicationSettingsModel();
                CreateFileUsingMemoryMap();
            }

            private void CreateFileUsingMemoryMap()
            {
                var info = Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "/" + model.Data.Settings.OrcaUISpecificSettings.TimeOutFolder);
                string path = Path.Combine(info.FullName + "/" + model.Data.Settings.OrcaUISpecificSettings.File);
                mmf = MemoryMappedFile.CreateFromFile(path, FileMode.CreateNew, "MyMemoryFile", 1024 * 1024, MemoryMappedFileAccess.ReadWrite);
            }

            public MemoryMappedViewAccessor GetAccessor()
            {
                MemoryMappedViewAccessor mmvAccessor = null;
                if (mmf != null)
                {
                    mmvAccessor = mmf.CreateViewAccessor();
                }
                return mmvAccessor;
            }
        }

    public partial class MainWindow : Window
        {
            private readonly DispatcherTimer _activityTimer;
            private Point _inactiveMousePosition = new Point(0, 0);
            private ApplicationSettingsViewModel AppViewModel;
            Mutex mutex = new Mutex(false, "OrcaGeneStudyMutex");
            public MainWindow()
            {
                InitializeComponent();
            }
            public void WriteToFile(string status)
            {
                Root root = new Root();
                root.AllApplications.Add(new DataToWrite() { AppName = "DevOrca", Status = status });
                var jsonString = JsonConvert.SerializeObject(root);
                var Accessor = AppViewModel.GetAccessor();
                mutex.WaitOne();
                //Serialize Contents

                Accessor.Write(1024, jsonString); //it gives a complilation error when i try to pass the json string,
            }
    }

0 个答案:

没有答案