Bin_Writer.cs

80 lines | 2.564 kB Blame History Raw Download
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

using ConfigurationTool.CustomSerializer;

using RW_Tool.Interface;
using RW_Tool.DataSource.FileOrStream;

namespace ConfigurationTool.RW.Bin
{
  

    public class Bin_Writer<T> : IWriter<T, DS_FileOrStream>
    {
        public void Write(T entity, DS_FileOrStream ds)
        {
            switch (ds.Type)
            {
                case "File": WriteFile(entity, ds.AsFile.FilePath); return;
                case "Stream": WriteStream(entity, ds.AsStream.Stream); return;

                default: throw new Exception();
            }
        }

        public void WriteFile(T entity, string file)
        {
            if (typeof(T).GetInterface("ICustomSerialazible") == null)
            {
                // передаем в конструктор тип класса
                BinaryFormatter formatter = new BinaryFormatter();

                // получаем поток, куда будем записывать сериализованный объект
                using (FileStream fs = new FileStream(file, FileMode.Create))
                {
                    formatter.Serialize(fs, entity);
                }
            }
            else
            {
                ICustomSerialazible ser = (ICustomSerialazible)entity;

                // передаем в конструктор тип класса
                BinaryFormatter formatter = new BinaryFormatter();

                // получаем поток, куда будем записывать сериализованный объект
                using (FileStream fs = new FileStream(file, FileMode.Create))
                {
                    formatter.Serialize(fs, ser.Export());
                }
            }
        }
        public void WriteStream(T entity, Stream stream)
        {
            if (typeof(T).GetInterface("ICustomSerialazible") == null)
            {
                // передаем в конструктор тип класса
                BinaryFormatter formatter = new BinaryFormatter();

                formatter.Serialize(stream, entity);
            }
            else
            {
                ICustomSerialazible ser = (ICustomSerialazible)entity;

                // передаем в конструктор тип класса
                BinaryFormatter formatter = new BinaryFormatter();

                formatter.Serialize(stream, ser.Export());
            }
        }
    }
}