PTMagic/Core/Helper/ZIPHelper.cs

106 lines
2.4 KiB
C#
Raw Normal View History

2018-05-22 10:11:50 +02:00
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using ICSharpCode.SharpZipLib.Zip;
2018-12-03 19:45:06 +01:00
namespace Core.Helper
{
2018-05-22 10:11:50 +02:00
2018-12-03 19:45:06 +01:00
public class ZIPHelper
{
public static bool CreateZipFile(ArrayList filePaths, string outputPath)
{
2018-05-22 10:11:50 +02:00
bool result = true;
ZipOutputStream pack = new ZipOutputStream(File.Create(outputPath));
2018-12-03 19:45:06 +01:00
try
{
2018-05-22 10:11:50 +02:00
// set compression level
pack.SetLevel(5);
2018-12-03 19:45:06 +01:00
foreach (string filePath in filePaths)
{
2018-05-22 10:11:50 +02:00
FileStream fs = File.OpenRead(filePath);
// allocate buffer
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
// write the zip entry and its data
ZipEntry entry = new ZipEntry(filePath.Substring(filePath.LastIndexOf(Path.DirectorySeparatorChar) + 1));
pack.PutNextEntry(entry);
pack.Write(buffer, 0, buffer.Length);
}
2018-12-03 19:45:06 +01:00
}
catch
{
2018-05-22 10:11:50 +02:00
result = false;
2018-12-03 19:45:06 +01:00
}
finally
{
2018-05-22 10:11:50 +02:00
pack.Finish();
pack.Close();
}
return result;
}
2018-12-03 19:45:06 +01:00
public static ArrayList ExtractFileFromZipFile(string filePath, string destinationPath, bool isInvoicePackage)
{
2018-05-22 10:11:50 +02:00
ArrayList result = new ArrayList();
ZipFile zip = new ZipFile(File.OpenRead(filePath));
2018-12-03 19:45:06 +01:00
try
{
foreach (ZipEntry entry in zip)
{
if (entry.IsFile)
{
2018-05-22 10:11:50 +02:00
string fileName = entry.Name;
2018-12-03 19:45:06 +01:00
if (isInvoicePackage)
{
2018-05-22 10:11:50 +02:00
fileName = fileName.Replace("unsigned", "signed");
}
result.Add(fileName);
Stream inputStream = zip.GetInputStream(entry);
FileStream fileStream = new FileStream(destinationPath + fileName, FileMode.Create);
2018-12-03 19:45:06 +01:00
try
{
2018-05-22 10:11:50 +02:00
CopyStream(inputStream, fileStream);
2018-12-03 19:45:06 +01:00
}
finally
{
2018-05-22 10:11:50 +02:00
fileStream.Close();
inputStream.Close();
}
}
}
2018-12-03 19:45:06 +01:00
}
finally
{
2018-05-22 10:11:50 +02:00
zip.Close();
}
return result;
}
2018-12-03 19:45:06 +01:00
private static void CopyStream(Stream input, Stream output)
{
2018-05-22 10:11:50 +02:00
byte[] buffer = new byte[0x1000];
int read;
2018-12-03 19:45:06 +01:00
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
2018-05-22 10:11:50 +02:00
output.Write(buffer, 0, read);
}
}
}
}