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;
namespace Core.Helper
{
2018-05-22 10:11:50 +02: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));
try
{
2018-05-22 10:11:50 +02:00
// set compression level
pack.SetLevel(5);
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);
}
}
catch
{
2018-05-22 10:11:50 +02:00
result = false;
}
finally
{
2018-05-22 10:11:50 +02:00
pack.Finish();
pack.Close();
}
return result;
}
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));
try
{
foreach (ZipEntry entry in zip)
{
if (entry.IsFile)
{
2018-05-22 10:11:50 +02:00
string fileName = entry.Name;
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);
try
{
2018-05-22 10:11:50 +02:00
CopyStream(inputStream, fileStream);
}
finally
{
2018-05-22 10:11:50 +02:00
fileStream.Close();
inputStream.Close();
}
}
}
}
finally
{
2018-05-22 10:11:50 +02:00
zip.Close();
}
return result;
}
private static void CopyStream(Stream input, Stream output)
{
2018-05-22 10:11:50 +02:00
byte[] buffer = new byte[0x1000];
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
2018-05-22 10:11:50 +02:00
output.Write(buffer, 0, read);
}
}
}
}