Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Dynamic;
- using System.IO;
- using System.Runtime.Serialization.Formatters.Binary;
- using System.Windows.Forms;
- namespace Polygons
- {
- public static class SaveLoadManager
- {
- private static readonly BinaryFormatter _binaryFormatter;
- private static readonly SaveFileDialog _saveFileDialog;
- private static readonly OpenFileDialog _openFileDialog;
- static SaveLoadManager()
- {
- _binaryFormatter = new BinaryFormatter();
- _saveFileDialog = new SaveFileDialog
- {
- AddExtension = true,
- CheckPathExists = true,
- DefaultExt = "plg"
- };
- _openFileDialog = new OpenFileDialog
- {
- Filter = "plg files (*.plg)|*.plg|All files (*.*)|*.*"
- };
- }
- public static void Save(IMemento obj, string directory = null)
- {
- if (obj == null) throw new ArgumentNullException(nameof(obj));
- if (directory != null) _saveFileDialog.InitialDirectory = directory;
- _saveFileDialog.FileName =
- DateTime.Now.Year + "-" +
- DateTime.Now.Month + "-" +
- DateTime.Now.Day + "_" +
- DateTime.Now.Hour + "-" +
- DateTime.Now.Minute + "_data";
- if (_saveFileDialog.ShowDialog() == DialogResult.OK)
- {
- Stream SaveFileStream = File.Create(_saveFileDialog.FileName);
- _binaryFormatter.Serialize(SaveFileStream, obj);
- SaveFileStream.Close();
- }
- }
- public static IMemento Load(string directory = null)
- {
- if (directory != null) _openFileDialog.InitialDirectory = directory;
- IMemento memento = null;
- if (_openFileDialog.ShowDialog() == DialogResult.OK && File.Exists(_openFileDialog.FileName))
- {
- Stream openFileStream = File.OpenRead(_openFileDialog.FileName);
- try
- {
- memento = (IMemento)_binaryFormatter.Deserialize(openFileStream);
- }
- catch
- {
- MessageBox.Show("Unable to find a plugin!");
- memento = null;
- }
- openFileStream.Close();
- }
- return memento;
- }
- }
- public interface IOriginator
- {
- IMemento CreateMemento();
- void SetMemento(in IMemento memento);
- }
- public interface IMemento
- {
- ExpandoObject GetState();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement