Feedback

C# - Lazy Serialization-Extensions including Compression

Veröffentlicht von am 1/22/2011
(0 Bewertungen)
Mit den beiden folgenden Extensions-Methods könnt Ihr beliebige Objekte komprimiert serialisieren. Ihr findet unten auch ein kleines Beispiel, wie ich eine ExampleSettings-Klasse serialisiere.
namespace CKing.Extensions
{
  using System.IO;
  using System.IO.Compression;
  using System.Runtime.Serialization.Formatters.Binary;
  using System.Xml.Serialization;

  public static class GenericExt
  {
    public static T Load<T>(this string path, bool binary)
    {
      try
      {
        if (path != null && File.Exists(path))
        {
          using (FileStream fs = new FileStream(path, FileMode.Open))
          {
            using (GZipStream zip = new GZipStream(fs, CompressionMode.Decompress))
            {
              if (!binary)
              {
                XmlSerializer xf = new XmlSerializer(typeof(T));
                return (T)xf.Deserialize(zip);
              }
              else
              {
                BinaryFormatter bf = new BinaryFormatter();
                return (T)bf.Deserialize(zip);
              }
            }
          }
        }
        return default(T);
      }
      catch
      {
        return default(T);
      }
    }

    public static bool Save<T>(this T obj, string path, bool binary)
    {
      try
      {
        DirectoryInfo di = new FileInfo(path).Directory;
        if (obj != null && di != null && di.Exists)
        {
          using (FileStream fs = new FileStream(path, FileMode.Create))
          {
            using (GZipStream zip = new GZipStream(fs, CompressionMode.Compress))
            {
              if (!binary)
              {
                XmlSerializer xf = new XmlSerializer(typeof(T));
                xf.Serialize(zip, obj);
              }
              else
              {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(zip, obj);
              }
            }
          }
          return true;
        }
        return false;
      }
      catch
      {
        return false;
      }
    }
  }
}

namespace CKing.Settings
{
  using System;
  using System.ComponentModel;

  [Serializable]
  public class ExampleSettings : INotifyPropertyChanged
  {
    #region Fields & Properties

    private string _exampleProperty1 = string.Empty;

    public string ExampleProperty1
    {
      get { return this._exampleProperty1; }
      set { this.SetNotifyingProperty("ExampleProperty1", ref this._exampleProperty1, value); }
    }

    private string _exampleProperty2 = string.Empty;

    public string ExampleProperty2
    {
      get { return this._exampleProperty2; }
      set { this.SetNotifyingProperty("ExampleProperty2", ref this._exampleProperty2, value); }
    }

    #endregion Fields & Properties

    #region INotifyPropertyChanged Member

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(String propertyName)
    {
      if (PropertyChanged != null)
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    private void SetNotifyingProperty<T>(string propertyName, ref T source, T value)
    {
      if (value.Equals(source))
        return;

      source = value;
      this.OnPropertyChanged(propertyName);
    }

    #endregion INotifyPropertyChanged Member
  }
}

namespace CKing.Application
{
  using System.IO;
  using System.Reflection;
  using CKing.Extensions;
  using CKing.Settings;

  class Program
  {
    static void Main(string[] args)
    {
      string appPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

      Program.SettingsPath = Path.Combine(appPath, "CKing.Application.set");
      Program.Settings = Program.SettingsPath.Load<ExampleSettings>(false);
      if (Program.Settings == null)
        Program.Settings = new ExampleSettings();

      Program.Settings.ExampleProperty1 = "Mal was speichern...";
      Program.Settings.ExampleProperty2 = "...und beim nächsten Start wird es wieder geladen.";

      if (!Program.Settings.Save<ExampleSettings>(Program.SettingsPath, false))
      {
        System.Diagnostics.Debug.WriteLine("An error occured while trying to save the Application-Settings");
      }
    }

    #region Properties

    internal static ExampleSettings Settings { get; set; }

    internal static string SettingsPath { get; set; }

    #endregion Properties
  }
}

Kommentare zum Snippet

 

Logge dich ein, um hier zu kommentieren!