Пример #1
0
 private static void Serialize(string fileName, MyStringData data)
 {
     using (var stream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
     {
         IFormatter formatter = CreateFormatter();
         formatter.Serialize(stream, data);
     }
 }
        static void Main(string[] args)
        {
            Console.WriteLine("***** Fun with Custom Serialization *****\n");

            #region Serialize MyStringData
            // Persist MyStringData in SOAP format.
            MyStringData sd = new MyStringData();
            sd.dataItemOne = "This is some data.";
            sd.dataItemTwo = "Here is some more data";

            Stream s = new FileStream("MyData.soap",
                                      FileMode.Create, FileAccess.Write, FileShare.None);

            SoapFormatter sf = new SoapFormatter();
            sf.Serialize(s, sd);
            s.Close();

            s  = File.OpenRead("MyData.soap");
            sd = (MyStringData)sf.Deserialize(s);
            Console.WriteLine("Item 1: {0}", sd.dataItemOne);

            Console.WriteLine("Item 2: {0}", sd.dataItemTwo);
            #endregion

            #region Serialize MoreData
            // Persist MoreData in SOAP format.
            MoreData md = new MoreData();
            md.dataItemOne = "Testing 1, 2, 3.";
            md.dataItemTwo = "One more test...";

            s = new FileStream("MoreData.soap",
                               FileMode.Create, FileAccess.Write, FileShare.None);

            sf = new SoapFormatter();
            sf.Serialize(s, md);
            s.Close();

            s  = File.OpenRead("MoreData.soap");
            md = (MoreData)sf.Deserialize(s);
            Console.WriteLine("Item 1: {0}", md.dataItemOne);
            Console.WriteLine("Item 2: {0}", md.dataItemTwo);
            Console.ReadLine();
            #endregion
        }
Пример #3
0
        static void Main(string[] args)
        {
            MyStringData original = new MyStringData
            {
                ItemOne = "Hello",
                ItemTwo = "World"
            };

            const string fileName = "serialized.bin";

            try
            {
                Serialize(fileName, original);

                var reconstructed = Deserialize(fileName);

                Console.WriteLine(IsEqual(original, reconstructed));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Пример #4
0
 private static bool IsEqual(MyStringData lhs, MyStringData rhs)
 {
     return
         (lhs.ItemOne == rhs.ItemOne &&
          lhs.ItemTwo == rhs.ItemTwo);
 }