// 从数据库读取dataset ,压缩写入 wenjian MssqlHelper db = new MssqlHelper(GlobalSetting.ConnectString); DataSet ds = db.ExecuteDataSet("select * from dim_goods"); byte[] bytesData = GetBytesFromDataSet(ds); byte[] byteCompress = CompressBytes(bytesData); WriteByteToFile(@"d:\temp\dim_goods9.zip", byteCompress);
//读取压缩文件, 还原为dataset byte[] bytesData = ReadFromFile(@"d:\temp\dim_goods9.zip"); byte[] byteCompress = Decompress(bytesData); DataSet ds = ByteArrayToDataSet(byteCompress);
public static byte[] GetBytesFromDataSet(DataSet ds) { byte[] data = null; using (MemoryStream stream = new MemoryStream()) { IFormatter bf = new BinaryFormatter(); ds.RemotingFormat = SerializationFormat.Binary; bf.Serialize(stream, ds); data = stream.ToArray(); } return data; } public static DataSet ByteArrayToDataSet(byte[] arrBytes) { MemoryStream memStream = new MemoryStream(); BinaryFormatter binForm = new BinaryFormatter(); memStream.Write(arrBytes, 0, arrBytes.Length); memStream.Seek(0, SeekOrigin.Begin); DataSet ds = (DataSet)binForm.Deserialize(memStream); return ds; } //压缩字节 //1.创建压缩的数据流 //2.设定compressStream为存放被压缩的文件流,并设定为压缩模式 //3.将需要压缩的字节写到被压缩的文件流 public static byte[] CompressBytes(byte[] bytes) { using (MemoryStream compressStream = new MemoryStream()) { using (var zipStream = new GZipStream(compressStream, CompressionMode.Compress)) zipStream.Write(bytes, 0, bytes.Length); return compressStream.ToArray(); } } //解压缩字节 //1.创建被压缩的数据流 //2.创建zipStream对象,并传入解压的文件流 //3.创建目标流 //4.zipStream拷贝到目标流 //5.返回目标流输出字节 public static byte[] Decompress(byte[] bytes) { using (var compressStream = new MemoryStream(bytes)) { using (var zipStream = new GZipStream(compressStream,CompressionMode.Decompress)) { using (var resultStream = new MemoryStream()) { zipStream.CopyTo(resultStream); return resultStream.ToArray(); } } } } public static byte[] ReadFromFile(string file) { FileStream fs = new FileStream(file, FileMode.Open, System.IO.FileAccess.Read); byte[] bytes = new byte[fs.Length]; fs.Read(bytes, 0, (int)fs.Length); return bytes; } public static void WriteByteToFile(string file , byte[] bytes) { FileStream fs = new FileStream(file, FileMode.Create, System.IO.FileAccess.Write); fs.Write(bytes, 0, bytes.Length); fs.Close(); }
标签:解压,读取,bytes,DataSet,new,byte,ds,MemoryStream From: https://www.cnblogs.com/easybi/p/17980257