1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74 | private void ZipBaks()
{
try
{
// Make sure directories exist
if (!Directory.Exists(BakPath))
Directory.CreateDirectory(BakPath);
if (!Directory.Exists(BakZipPath))
Directory.CreateDirectory(BakZipPath);
// Clean up old zip files
string[] bakfiles = Directory.GetFiles(BakPath, "*" + BakExtension);
string[] bakzipfiles = Directory.GetFiles(BakZipPath, "*" + ZipExtension);
foreach (string bakzipfile in bakzipfiles)
{
string bakzipfilename = bakzipfile.Substring(bakzipfile.LastIndexOf(@"\") + 1);
string bakfilename = bakzipfilename.Substring(0, bakzipfilename.LastIndexOf('.'));
if (!File.Exists(BakPath + @"\" + bakfilename))
{
ToLog("Deleting Zip File: " + bakzipfile);
File.Delete(bakzipfile);
}
}
// Create new zip files as necssary
foreach (string bakfile in bakfiles)
{
string ZipFile = BakZipPath + @"\" + bakfile.Substring(bakfile.LastIndexOf(@"\") + 1) + ZipExtension;
if (!File.Exists(ZipFile))
{
ToLog("Creating Zip File: " + ZipFile);
using (ZipOutputStream s = new ZipOutputStream(File.Create(ZipFile)))
{
s.SetLevel(9); // 0 - store only to 9 - means best compression
byte[] buffer = new byte[4096];
// Using GetFileName makes the result compatible with XP
// as the resulting path is not absolute.
ZipEntry entry = new ZipEntry(Path.GetFileName(bakfile));
// Setup the entry data as required.
// Crc and size are handled by the library for seakable streams
// so no need to do them here.
// Could also use the last write time or similar for the file.
entry.DateTime = DateTime.Now;
s.PutNextEntry(entry);
using (FileStream fs = File.OpenRead(bakfile))
{
// Using a fixed size buffer here makes no noticeable difference for output
// but keeps a lid on memory usage.
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0, buffer.Length);
s.Write(buffer, 0, sourceBytes);
} while (sourceBytes > 0);
}
// Finish/Close arent needed strictly as the using statement does this automatically
// Finish is important to ensure trailing information for a Zip file is appended. Without this
// the created file would be invalid.
s.Finish();
// Close is important to wrap things up and unlock the file.
s.Close();
}
}
}
}
|