使用Compression對檔案流進行壓縮後寫入資料庫
阿新 • • 發佈:2018-11-30
檔案轉換成二進位制流後,將二進位制流儲存到資料庫相應的欄位中,檔案稍大時,將嚴重影響資料庫的效能
因此,我們可以將檔案進行壓縮後在進行儲存.
這裡我們使用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); } }
至於怎麼將位元組陣列怎麼寫入資料庫的表中,可以參考的檔案有很多,這裡不再描述了