博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C# 将对象保存为文件 读取文件并转为对象 压缩文件 解压缩文件
阅读量:4516 次
发布时间:2019-06-08

本文共 10464 字,大约阅读时间需要 34 分钟。

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
(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
(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
(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
(_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 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
(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); // } //} ///
/// 压缩指定文件 /// ///
rar.exe文件名 ///
指定要压缩的文件名 ///
指定要生成的压缩包名称(可选) ///
bool
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; } } ///
/// 假定当前运行目录下存在rar.exe文件的情况下,将指定的.rar文件解压到指定目录 /// ///
指定的.rar文件 ///
要解压到的目录 ///
bool
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; } } }}

 

转载于:https://www.cnblogs.com/kenchan/p/4684766.html

你可能感兴趣的文章
Python MySQL Django一些问题
查看>>
OpenGL------显示列表
查看>>
『科学计算』高斯判别分析模型实现
查看>>
『Pickle』数据结构持久化模块_常用方法记录
查看>>
pycharm 的包路径设置export PYTHONPATH=$PYTHONPATH
查看>>
SQL语句创建函数
查看>>
查找数组元素位置
查看>>
vue开发的打包配置
查看>>
jquery基础
查看>>
端口作用
查看>>
不同web应用登录方案
查看>>
利用css制作横向和纵向时间轴
查看>>
Generic(泛型)
查看>>
009 如何更好地进行沟通
查看>>
NFC NDEF vcard
查看>>
mininet test
查看>>
OOP
查看>>
找出数组中的重复元素
查看>>
Apache服务器配置
查看>>
ClickOnce清单签名取消后依然读取证书的问题
查看>>