Bin_Reader.cs

84 lines | 2.541 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_Reader<T> : IReader<T, DS_FileOrStream>
        where T : class, new()
    {
        public T Read(DS_FileOrStream ds)
        {
            switch (ds.Type)
            {
                case "File": return ReadFile(ds.AsFile.FilePath);
                case "Stream": return ReadStream(ds.AsStream.Stream);

                default: throw new Exception();
            }
        }

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

                // десериализация
                using (FileStream fs = new FileStream(file, FileMode.Open))
                {
                    return (T)formatter.Deserialize(fs);
                }
            }
            else
            {
                ICustomSerialazible res = (ICustomSerialazible)new T();

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

                // десериализация
                using (FileStream fs = new FileStream(file, FileMode.Open))
                {
                    res.Import(formatter.Deserialize(fs));
                }

                return (T)res;
            }
        }
        public T ReadStream(Stream stream)
        {
            if (typeof(T).GetInterface("ICustomSerialazible") == null)
            {
                // передаем в конструктор тип класса
                BinaryFormatter formatter = new BinaryFormatter();

                // десериализация                
                return (T)formatter.Deserialize(stream);
            }
            else
            {
                ICustomSerialazible res = (ICustomSerialazible)new T();

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

                // десериализация
                res.Import(formatter.Deserialize(stream));

                return (T)res;
            }
        }
    }
}