98 lines
3.8 KiB
C#
98 lines
3.8 KiB
C#
using System;
|
|
using System.IO;
|
|
using ICSharpCode.SharpZipLib.Zip;
|
|
|
|
namespace dezentrale
|
|
{
|
|
public class ImportExport
|
|
{
|
|
public static bool ZipExport(string outFile, string password = null)
|
|
{
|
|
if (!Directory.Exists(Program.config.MemberDirectory))
|
|
{
|
|
Console.WriteLine($"Cannot find directory '{Program.config.MemberDirectory}'");
|
|
return false;
|
|
}
|
|
try
|
|
{
|
|
// Depending on the directory this could be very large and would require more attention
|
|
// in a commercial package.
|
|
string[] filenames = Directory.GetFiles(Program.config.MemberDirectory, "member-*.xml");
|
|
|
|
if (File.Exists(outFile))
|
|
{
|
|
string backupName = $"{outFile}.bak";
|
|
if (File.Exists(backupName)) File.Delete(backupName);
|
|
File.Move(outFile, backupName);
|
|
}
|
|
|
|
// 'using' statements guarantee the stream is closed properly which is a big source
|
|
// of problems otherwise. Its exception safe as well which is great.
|
|
using (ZipOutputStream s = new ZipOutputStream(File.Create(outFile)))
|
|
{
|
|
/*#if DEBUG
|
|
s.SetLevel(0); // 0 - store only to 9 - means best compression
|
|
#else*/
|
|
s.SetLevel(9); // 0 - store only to 9 - means best compression
|
|
//#endif
|
|
s.Password = password; //null is a desired value for "no encryption"
|
|
|
|
byte[] buffer = new byte[4096];
|
|
|
|
foreach (string file in filenames)
|
|
{
|
|
|
|
// Using GetFileName makes the result compatible with XP
|
|
// as the resulting path is not absolute.
|
|
var entry = new ZipEntry(Path.GetFileName(file));
|
|
|
|
// 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(file))
|
|
{
|
|
|
|
// 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();
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"Exception during processing {ex.Message}");
|
|
|
|
// No need to rethrow the exception as for our purposes its handled.
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
public static bool ZipImport(string inFile, string password = null)
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
}
|