码迷,mamicode.com
首页 > Windows程序 > 详细

C# 将对象保存为文件 读取文件并转为对象 压缩文件 解压缩文件

时间:2015-07-29 00:55:53      阅读:267      评论:0      收藏:0      [点我收藏+]

标签:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO.Compression;
using System.Diagnostics;

namespace chmPrinter
{
    public class SaveFile
    {
        public SaveFile()
        { }

        private static SaveFile _instance;
        public static SaveFile Instance
        {
            get
            {
                if (_instance == null) _instance = new SaveFile();
                return _instance;
            }
        }

        public object GetObjectData(string filename)
        {
            Stream Read = null;
            string strErr = "";

            try
            {
                FileInfo FI = new FileInfo(filename);

                if (FI.Exists)
                {
                    Read = FI.OpenRead();
                    BinaryFormatter BF = new BinaryFormatter();

                    byte[] aa = (byte[])BF.Deserialize(Read);

                    return DecompressToObject(aa);
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                strErr = ex.ToString();
            }
            finally
            {
                if (Read != null)
                {
                    Read.Close();
                }
            }
            return null;
        }

        //新方法
        public T GetObject<T>(string filename)
        {
            object obj = GetObjectData(filename);
            if (obj != null)
            {
                return (T)obj;
            }
            return default(T);

            //Stream Read = null;
            //string strErr = "";

            //try
            //{
            //    FileInfo FI = new FileInfo(filename);

            //    if (FI.Exists)
            //    {
            //        Read = FI.OpenRead();
            //        BinaryFormatter BF = new BinaryFormatter();

            //        byte[] aa = (byte[])BF.Deserialize(Read);

            //        return DecompressToObject<T>(aa);
            //    }
            //    else
            //    {
            //        return default(T);
            //    }
            //}
            //catch (Exception ex)
            //{
            //    strErr = ex.ToString();
            //}
            //finally
            //{
            //    if (Read != null)
            //    {
            //        Read.Close();
            //    }
            //}
            //return default(T);
        }

        public void SaveObjectData(string filename, object _data)
        {
            Stream Write = null;
            try
            {
                FileInfo FI = new FileInfo(filename);
                if (FI.Exists) FI.Delete();
                Write = FI.OpenWrite();
                BinaryFormatter BF = new BinaryFormatter();
                byte[] aa = CompressedToBytes(_data);
                BF.Serialize(Write, aa);
            }
            catch (Exception ex)
            {
                string str = ex.Message;
            }
            finally
            {
                if (Write != null)
                {
                    Write.Close();
                }
            }
        }

        //新方法
        public void SaveObject<T>(string filename, T _data)
        {
            SaveObjectData(filename, _data);

            //Stream Write = null;
            //try
            //{
            //    FileInfo FI = new FileInfo(filename);
            //    if (FI.Exists) FI.Delete();
            //    Write = FI.OpenWrite();
            //    BinaryFormatter BF = new BinaryFormatter();
            //    byte[] aa = CompressedToBytes<T>(_data);
            //    BF.Serialize(Write, aa);
            //}
            //catch (Exception ex)
            //{
            //    string str = ex.Message;
            //}
            //finally
            //{
            //    if (Write != null)
            //    {
            //        Write.Close();
            //    }
            //}
        }


        private byte[] CompressedToBytes(object obj)
        {
            MemoryStream ms = new MemoryStream();
            DeflateStream zip = new DeflateStream(ms, CompressionMode.Compress, true);
            try
            {
                BinaryFormatter serializer = new BinaryFormatter();
                serializer.Serialize(zip, obj);
                zip.Close();
                byte[] ary = ms.ToArray();
                ms.Close();
                return ary;
            }
            catch (Exception )
            {
                //Log.write(e.Message);
                zip.Close();
                ms.Close();
                return null;
            }
        }

        //新方法
        //private byte[] CompressedToBytes<T>(T obj)
        //{
        //    MemoryStream ms = new MemoryStream();
        //    DeflateStream zip = new DeflateStream(ms, CompressionMode.Compress, true);
        //    try
        //    {
        //        BinaryFormatter serializer = new BinaryFormatter();
        //        serializer.Serialize(zip, obj);
        //        zip.Close();
        //        byte[] ary = ms.ToArray();
        //        ms.Close();
        //        return ary;
        //    }
        //    catch (Exception e)
        //    {
        //        //Log.write(e.Message);
        //        zip.Close();
        //        ms.Close();
        //        return null;
        //    }
        //}

        private object DecompressToObject(byte[] ary)
        {
            MemoryStream ms = new MemoryStream(ary);
            DeflateStream UnZip = new DeflateStream(ms, CompressionMode.Decompress);

            try
            {
                BinaryFormatter serializer = new BinaryFormatter();
                object obj = serializer.Deserialize(UnZip);
                UnZip.Close();
                ms.Close();
                return obj;
            }
            catch (Exception )
            {
                //Log.write(e.Message);
                UnZip.Close();
                ms.Close();
                return null;
            }
        }

        //新方法
        //private T DecompressToObject<T>(byte[] ary)
        //{
        //    MemoryStream ms = new MemoryStream(ary);
        //    DeflateStream UnZip = new DeflateStream(ms, CompressionMode.Decompress);

        //    try
        //    {
        //        BinaryFormatter serializer = new BinaryFormatter();
        //        object obj = serializer.Deserialize(UnZip);
        //        UnZip.Close();
        //        ms.Close();
        //        return (T)obj;
        //    }
        //    catch (Exception e)
        //    {
        //        //Log.write(e.Message);
        //        UnZip.Close();
        //        ms.Close();
        //        return default(T);
        //    }
        //}


        /// <summary>
        /// 压缩指定文件
        /// </summary>
        /// <param name="rarexefile">rar.exe文件名</param>
        /// <param name="rarFilename">指定要压缩的文件名</param>
        /// <param name="archfile">指定要生成的压缩包名称(可选)</param>
        /// <returns>bool</returns>
        public bool inRarFile(string rarexefile, string rarFilename, string archfile)
        {
            try
            {
                string[] paths = rarFilename.Split(\\);
                string _strPath = rarFilename.Substring(0, rarFilename.Length - paths[paths.Length - 1].Length);
                string _filename = paths[paths.Length - 1].ToString();

                if (_filename.ToLower().EndsWith("rar.exe")) return true;

                FileInfo rar = new FileInfo(rarexefile);

                if (!rar.Exists) return false;

                FileInfo rarfile = new FileInfo(rarFilename);

                if (!rarfile.Exists) return false;

                Process tempPro = new Process();
                tempPro.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                tempPro.StartInfo.FileName = rarexefile;
                tempPro.StartInfo.WorkingDirectory = _strPath;
                if (archfile.Trim().Equals(""))
                {
                    tempPro.StartInfo.Arguments = "a " + "\"" + _filename + ".rar" + "\" " + "\"" + _filename + "\"";
                }
                else
                {
                    tempPro.StartInfo.Arguments = "a " + "\"" + archfile + "\" " + "\"" + _filename + "\"";
                }
                tempPro.Start();
                tempPro.WaitForExit();
                return true;
            }
            catch (Exception )
            {
                return false;
            }
        }

        /// <summary>
        /// 假定当前运行目录下存在rar.exe文件的情况下,将指定的.rar文件解压到指定目录
        /// </summary>
        /// <param name="rarFilename">指定的.rar文件</param>
        /// <param name="_topath">要解压到的目录</param>
        /// <returns>bool</returns>
        public bool outRarFile(string rarFilename, string _topath)
        {
            try
            {
                FileInfo rar = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "rar.exe");
                if (!rar.Exists) return false;

                FileInfo rarfile = new FileInfo(rarFilename);
                if (!rarfile.Exists) return false;

                Process tempPro = new Process();
                tempPro.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                tempPro.StartInfo.FileName = rar.FullName;
                tempPro.StartInfo.WorkingDirectory = _topath;
                tempPro.StartInfo.Arguments = "x " + rarFilename + " -y -v -r -o+";
                tempPro.Start();
                tempPro.WaitForExit();
                System.Threading.Thread.Sleep(1000);

                return true;
            }
            catch (Exception ee)
            {
                string str = ee.Message;
                return false;
            }
        }

        
        public bool Rarpath(string rarexefile, string rarFilename, string archfile)
        {
            try
            {
                string[] paths = rarFilename.Split(\\);
                string _strPath = rarFilename.Substring(0, rarFilename.Length - paths[paths.Length - 1].Length);
                string _filename = paths[paths.Length - 1].ToString();

                DirectoryInfo _pathinfo = new DirectoryInfo(rarFilename);
                if (!_pathinfo.Exists) return false;

                FileInfo rar = new FileInfo(rarexefile);

                if (!rar.Exists) return false;

                Process tempPro = new Process();
                tempPro.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                tempPro.StartInfo.FileName = rarexefile;
                tempPro.StartInfo.WorkingDirectory = _strPath;

                if (archfile.Trim().Equals(""))
                {
                    tempPro.StartInfo.Arguments = " a " + "\"" + _filename + ".rar" + "\" " + "\"" + _filename + "\"";
                }
                else
                {
                    tempPro.StartInfo.Arguments = " a -ap " + "\"" + archfile + "\" " + "\"" + _filename + "\"";
                }
                tempPro.Start();
                tempPro.WaitForExit();
                return true;
            }
            catch (Exception )
            {
                return false;
            }
        }

        public bool Rarpathfiles(string rarexefile, string rarFilename, string _filefilter, string archfile)
        {
            try
            {
                string[] paths = rarFilename.Split(\\);
                string _strPath = rarFilename.Substring(0, rarFilename.Length - paths[paths.Length - 1].Length);
                string _filename = paths[paths.Length - 1].ToString();

                DirectoryInfo _pathinfo = new DirectoryInfo(rarFilename);
                if (!_pathinfo.Exists) return false;

                FileInfo rar = new FileInfo(rarexefile);

                if (!rar.Exists) return false;

                Process tempPro = new Process();
                tempPro.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                tempPro.StartInfo.FileName = rarexefile;
                tempPro.StartInfo.WorkingDirectory = rarFilename;

                if (archfile.Trim().Equals(""))
                {
                    tempPro.StartInfo.Arguments = " a " + "\"" + _filename + ".rar" + "\" " + "\"" + _filefilter + "\"";
                }
                else
                {
                    tempPro.StartInfo.Arguments = " a -ap " + "\"" + archfile + "\" " + "\"" + _filefilter + "\"";
                }
                tempPro.Start();
                tempPro.WaitForExit();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}

 

C# 将对象保存为文件 读取文件并转为对象 压缩文件 解压缩文件

标签:

原文地址:http://www.cnblogs.com/kenchan/p/4684766.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!