使用Compression对文件流进行压缩后写入数据库

文件转换成二进制流后,将二进制流保存到数据库相应的字段中,文件稍大时,将严重影响数据库的性能
因此,我们可以将文件进行压缩后在进行存储.
这里我们使用System.IO 中的Compression类进行压缩
(在 4.5 之前,处理压缩文件,我们经常需要使用第三方的类库 SharpZipLib)
对文件进行压缩,返回字节数组

  public static byte[] Compression(string filePathAndName)
        {
            using (FileStream fs = new FileStream(filePathAndName, FileMode.Open,
               FileAccess.Read))
            {
                byte[] FileByte = new byte[fs.Length];
                fs.Read(FileByte, 0, FileByte.Length);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (GZipStream Gzip = new GZipStream(ms, CompressionMode.Compress, true))
                    {
                      		//将压缩文件字节写入内存流中
                        Gzip.Write(FileByte, 0, FileByte.Length);

                    }
                    //不知道什么原因,注释掉的部分读取到字节数组内的值全是0,后来发现使用ms.toArray() 可以正确读取
                    //byte[] compressFileByte2 = new byte[ms.Length];
                    //ms.Read(compressFileByte2, 0, compressFileByte2.Length);
                   // 返回内存流的字节数组
                    return ms.ToArray();
                }
            }
        }

将从数据库读取到的压缩的字节数组转为文件保存

 public static void Decompression(byte[] compressionDataByte, string LoadfilePathAndName)
        {
            byte[] decopressFileByte;
            using (MemoryStream ms= new MemoryStream(compressionDataByte))
            {
                GZipStream Gzip2 = new GZipStream(ms, CompressionMode.Decompress, true);            \
                //这里没有使用 Gzip.ReadGzip2.Read(decopressFileByte, 0, decopressFileByte.Length); 这种方法进行读取,因为不知道解压后字节数组为多大,需要使用List<byte> 中add方法一个个加入,很麻烦,所以使用了BinaryFormatter中的反序列化直接转为二进制形式
                BinaryFormatter bf = new BinaryFormatter();
                decopressFileByte=(byte[])bf.Deserialize(Gzip2);
            }
            using (FileStream fs2 = new FileStream(LoadfilePathAndName, FileMode.Create, FileAccess.Write))
            {
                fs2.Write(decopressFileByte, 0, decopressFileByte.Length);
            }
        }

至于怎么将字节数组怎么写入数据库的表中,可以参考的文件有很多,这里不再描述了

猜你喜欢

转载自blog.csdn.net/Good_StudyDaydayUp/article/details/82981457