Willkommen bei dotnet-snippets.de! Snippet hinzufügen Login Registrieren
Snippets in der Datenbank: 1563 | Anzahl registrierter User: 1895 | Besucher online: 187
Hauptmenü
Home
Top Ten
Zufälliger Snippet
FAQs
.NET Community
dotnet-forum.de
dotnet-kicks.de
Social

RSS Feeds
Rss Alle Snippets
Rss C#
Rss VB.NET
Rss C++
Rss ASP.NET
Partner
Member of Microsoft Community Leader/Insider Program (CLIP)

Lazy Serialization-Extensions including Compression


Autor: Christian Köwing
Sprache: C#
Bewertung:
noch nicht bewertet
Anzahl der Aufrufe: 2512
  
Kick it on dotnet-kicks.de  

Beschreibung:

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.

Abgelegt unter: Lazy, Serialization, Deserialization, XmlSerializer, BinaryFormatter, Compression, GZipStream, Extension, INotifyPropertyChanged.



C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
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
  }
}
Sie haben Fragen zu diesem Snippet oder brauchen Hilfe bei der .NET Entwicklung?
Freundliche und kompetente Entwickler helfen Ihnen gern weiter im Forum für .NET Entwicklung.



Kommentare:
(Zum Schreiben von Kommentaren bitte anmelden.)



Diese Snippets könnten für Sie interessant sein:
[C#] generische zip funktion
[C#] IsNull and IsNullOrEmpty Extension-Methods become Lazy
[C#] Zum De/Serialisieren von Objekten
[C#] generische De-/ Serialisierung von Objekten in XML und Binär
[C#] Fast & Easy to use serializable Settings-Class
[C#] Objekt in XML speichern (Serialisieren)
[C#] Objekt Serialisieren mit UTF-8 encoding
[VB.NET] ByteArray mit dem BinaryFormatter deserialisieren
[VB.NET] Objekt mit dem BinaryFormatter serialisieren
[C#] Generisches, komprimiertes, serialisieren von Objekten
[C#] Generisches, komprimiertes, deserialisieren von Objekten
[C#] Datei/Ordner durch Erweiterungsmethoden abfragen
[C#] Programmpfad mittels Erweiterung ermitteln
[C#] Invoke Beispiel mittels Erweiterungs Methoden.
[C#] DateTime Extensions liefern TimeStamp
[C#] Komplette Exception Message (inkl. InnerExceptions) ausgeben
[VB.NET] Programmpfad mittels Erweiterung ermitteln in VB
[C#] LINQ-Erweiterung für eindeutige Liste
[C#] Type Color serialisieren und deserialisieren
[C#] Controls gleichen Typs von einem Container in Winform holen
[C#] Extension in einem Dateinamen/Pfad ändern
[C#] Threadsicherer Codeaufruf im Control-Kontext (Invoking)
[C#] Selektieren eines gekapselten Eintrags aus der ComboBox
[C#] Color Extension-Methods
[C#] Enum-Extension - Flag in einem Bitfeld gesetzt?
[C#] Anzahl der Monate zwischen 2 DateTime-Objekten (Extension)
[C#] "for" mal anders
[C#] Generische Event Args -> EventArgs
[C#] SystemIconsImageListWrapper
[C#] Wie ToString() welche mit null-Strings umgehen kann
[C#] Eingabefelder mit Daten in WPF verknüpfen (Data Binding)
[C#] INotifyPropertyChanged implementation with event pattern
[C#] Namen von Klassenmember als String ermitteln
[C#] INotifyPropertyChanged Implementierung mit IsChanged Events

schlecht sehr gut
1 2 3 4 5 6 7 8 9 10
Nur angemeldete User können Snippets bewerten.