Zip for WPF and Silverlight
C1Zip Tutorials / Compressed Serialization
In This Topic
    Compressed Serialization
    In This Topic

    This tutorial shows how you can serialize objects in compressed files, and then load them back into the memory.

    The sample creates a data table of people. The table is saved (serialized) into regular and compressed streams. Finally, the data is loaded back from either stream. Here is what the final application will look like:

     

     

    Step 1: Create the main form.

    Start a new WPF or Silverlight project in Visual Studio and from the Toolbox, add the following controls to the form:

    Step 2: Create the data file.

    Right-click on your project name in the Solution Explorer and select Add | New Item from the menu. Select Code File from the list and name the file Data.cs.

    At the top of the Data.cs file, add the following statements:

    C#
    Copy Code
    using System;   
    using System.Net;   
    using System.Windows;   
    using System.Windows.Controls;   
    using System.Windows.Documents;   
    using System.Windows.Ink;   
    using System.Windows.Input;   
    using System.Windows.Media;   
    using System.Windows.Media.Animation;   
    using System.Windows.Shapes;   
    using System.Runtime.Serialization;   
    using System.Collections.Generic;
    

    Use your project name when adding a namespace declaration:

    C#
    Copy Code
    namespace [Your Project Name]
    

    Add the following code below the namespace declaration:

    C#
    Copy Code
    {   
                  [Serializable]   
            public class Person   
           {  
     
            public string FirstName   
            {   
                get;   
                set;   
            }  
       
            public string LastName   
            {   
                get;   
                set;   
            }
       
            public int Age   
            {   
                get;   
                set;   
            }
       
            public string City   
            {   
                get;   
                set;   
            }   
        }
       
           [Serializable]   
           public class PersonList    
           {   
            private List<Person> _persons = new List<Person>();  
             public List<Person> Persons  
            {   
                get   
                {   
                    return this._persons;   
                }   
                set   
                {   
                    this._persons = value;   
                }   
            }   
        }   
    }
    

    This adds the necessary code file to your project.

    Step 3: Add references and using statements.

    Go to the Solution Explorer window and click the Show All Files button. Right-click on References, and select the Add Reference menu option. Select the C1.WPF.Zip or C1.Silverlight.Zip assembly from the list, or browse to find the C1.WPF.Zip.dll or C1.Silverlight.Zip.dll file.

    Select the MainPage.xaml.vb or MainWindow.xaml.cs tab or go to View|Code to open the Code Editor. At the top of the file, add the following statements:

    Visual Basic
    Copy Code
    Imports System.IO
    Imports System.Runtime.Serialization.Formatters.Binary
    Imports C1.C1Zip
    

     

    C#
    Copy Code
    using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;
    using C1.C1Zip;
    

    This declares the namespaces of the classes used in the project.

    Step 4: Declare constants.

    In the Code Editor of the window, type or copy the following lines in the body of the window implementation:

    C#
    Copy Code
    public partial class MainWindow : Window
                  {
            private const string FN_REGULAR = @"\regular";
            private const string FN_COMPRESSED = @"\compressed";
            PersonList personList = new PersonList();
    

    These constants define the name of the database used to populate the data table and the file names used to serialize the data.

    Step 5: Add code to create the data table.

    Add the following code to handle the Click event for the Create Data button:

    C#
    Copy Code
    private void btnCreate_Click(object sender, RoutedEventArgs e)
            {
                for (int i = 0; i < 1000; i++)
                {
                    personList.Persons.Add(new Person()
                    {
                      FirstName = string.Format("First Name {0}", i),
                      LastName = string.Format("Last Name {0}", i),
                      Age = i,
                      City = string.Format("City {0}", i)
                    });
                }
                this.dataGrid1.ItemsSource = personList.Persons;
            }
    

    The function populates the DataGrid using the Data.cs file you created previously.

    Step 6: Add code to save the data.

    Add the following code to handle the Click event for the Save Data button:

    C#
    Copy Code
    private void btnSave_Click(object sender, RoutedEventArgs e)
            {
                // Show status.   
                Cursor = Cursors.Wait;   
                label1.Content = "Serializing data to regular file..."; 
                // Serialize the data set to a regular file.
                string fn = Environment.CurrentDirectory + FN_REGULAR; 
                FileStream fs = new FileStream(fn, FileMode.Create);
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(fs, personList);  
                long lenRegular = fs.Length;
                fs.Close();  
                // Show status.   
                Cursor = Cursors.Wait;
                label1.Content = "Serializing data to compressed file...";    
                // Serialize the data set to a compressed file.  
                fn = Environment.CurrentDirectory + FN_COMPRESSED;   
                fs = new FileStream(fn, FileMode.Create);  
                C1ZStreamWriter compressor = new C1ZStreamWriter(fs);  
                bf = new BinaryFormatter();   
                bf.Serialize(compressor, personList);  
                long lenCompressed = fs.Length;   
                fs.Close();    
                // Show status.   
                Cursor = Cursors.Hand;   
                label1.Content = string.Format("Saved to regular file ({0:#,###} bytes) and " + "compressed file ({1:#,###} bytes)", lenRegular, lenCompressed);  
                // Enable the load buttons.   
                btnLoad.IsEnabled = true;
                btnLoadCompressed.IsEnabled = true;
            }
    

    The first set of code serializes the data into a regular file, and the second serializes the data into a compressed file. Note that only one additional line is required to compress the data.

    In both cases, the serialization is executed by the BinaryFormatter object. The only difference is that in the first case, the Serialize method is called with a regular file stream as a parameter; in the second, a C1ZStreamWriter is used instead.

    Step 7: Add code to load the data table from the regular file.

    Add the following code to handle the Click event for the Load Data button:

    C#
    Copy Code
    private void btnLoad_Click(object sender, RoutedEventArgs e)
            {
                // Clear grid, show status.   
                Cursor = Cursors.Wait;
                dataGrid1.ItemsSource = null;  
                label1.Content = "Loading from regular file...";   
                // Deserialize from regular file.   
                string fn = Environment.CurrentDirectory + FN_REGULAR;   
                FileStream fs = new FileStream(fn, FileMode.Open);  
                long ticks = DateTime.Now.Ticks;   
                BinaryFormatter bf = new BinaryFormatter();   
                PersonList pl = (PersonList)bf.Deserialize(fs);   
                long ms = (DateTime.Now.Ticks - ticks) / TimeSpan.TicksPerMillisecond;   
                fs.Close();    
                // Show result.   
                Cursor = Cursors.Hand;   
                dataGrid1.ItemsSource = pl.Persons; 
                label1.Content = "Loaded from regular file in " + ms.ToString() + " ms.";
            }
    

    Step 8: Add code to load the data from the compressed file.

    Add the following code to handle the Click event for the Load Compressed Data button:

    C#
    Copy Code
    private void btnLoadCompressed_Click(object sender, RoutedEventArgs e)
            {
                // Clear grid, show status.   
                Cursor = Cursors.Wait;   
                dataGrid1.ItemsSource = null;
                label1.Content = "Loading from compressed file...";
                // Deserialize from compressed file.   
                string fn = Environment.CurrentDirectory + FN_COMPRESSED;   
                FileStream fs = new FileStream(fn, FileMode.Open);   
                long ticks = DateTime.Now.Ticks;   
                C1ZStreamReader decompressor;   
                decompressor = new C1ZStreamReader(fs);   
                BinaryFormatter bf = new BinaryFormatter();
                PersonList pl = (PersonList)bf.Deserialize(decompressor);
                long ms = (DateTime.Now.Ticks - ticks) / TimeSpan.TicksPerMillisecond; fs.Close();
                // Show result.   
                Cursor = Cursors.Hand;   
                dataGrid1.ItemsSource = pl.Persons;   
                label1.Content = "Loaded from compressed file in " + ms.ToString() + " ms.";
            }
        }
    }
    

    The main lines are similar to the code used to deserialize data from a regular file. The only difference is that instead of passing a regular file stream to the Deserialize method, we now use a C1ZStreamReader object.

    This concludes the Compressed Serialization tutorial.