Sometimes you just have to save files in the database. The reason? Because "Simon" said so. So without further ado, here is a simple example on how to compress files using C# and SharpZipLib:
1
2 using System;
3 using System.IO;
4 using ICSharpCode.SharpZipLib.Zip.Compression;
5 using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
6
7 namespace YourNamespace {
8 public class GenericCompressor {
9 public static byte[] Compress(byte[] buffer) {
10 MemoryStream ms = new MemoryStream();
11
12 Stream stream = new DeflaterOutputStream(
13 ms,
14 new Deflater(Deflater.BEST_COMPRESSION),
15 buffer.Length
16 );
17
18 try {
19 stream.Write(buffer, 0, buffer.Length);
20 }
21 finally {
22 stream.Close();
23 stream.Dispose();
24 }
25
26 return ms.ToArray();
27 }
28
29 public static byte[] Decompress(byte[] buffer) {
30 MemoryStream ms = new MemoryStream();
31 byte[] data = new byte[4096];
32
33 Stream stream = new InflaterInputStream(
34 new MemoryStream(buffer)
35 );
36
37 try {
38 while (true) {
39 int bytes = stream.Read(data, 0, data.Length);
40
41 if (bytes < 1) {
42 break;
43 }
44
45 ms.Write(data, 0, bytes);
46 }
47 }
48 finally {
49 stream.Close();
50 stream.Dispose();
51 }
52
53 return ms.ToArray();
54 }
55 }
56 }
To compress files in ASP.Net, the code would be something like this:
1
2 byte[] data = new byte[fileUpload.PostedFile.ContentLength];
3
4 fileUpload.PostedFile.InputStream.Read(data, 0, data.Length);
5
6 byte[] compressedData = GenericCompressor.Compress(data);
7
8 // Then save to your favorite database...
Conclusion:
I prefer having this utility over other solutions because I don't have to be tied up to a specific database vendor and of course, no database component or assembly to install. No hassle.