You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

45 lines
1.4 KiB
C#

using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Rs.MotionPlat.Commom
{
public class ZipHelper
{
public static void ZipDirectory(string folderPath, string zipPath)
{
if (!Directory.Exists(folderPath))
throw new DirectoryNotFoundException($"The directory {folderPath} could not be found.");
using (var zipFile = ZipFile.Create(zipPath))
{
var zipDirEntry = Path.GetFileName(folderPath);
zipFile.BeginUpdate();
AddDirectoryToZip(zipFile, folderPath, zipDirEntry);
zipFile.CommitUpdate();
}
}
private static void AddDirectoryToZip(ZipFile zipFile, string folderName, string zipDirEntry)
{
var files = Directory.GetFiles(folderName);
foreach (var file in files)
{
var entry = Path.Combine(zipDirEntry, Path.GetFileName(file)).Replace('\\', '/');
zipFile.Add(file, entry);
}
var subdirs = Directory.GetDirectories(folderName);
foreach (var subdir in subdirs)
{
var entry = Path.Combine(zipDirEntry, Path.GetFileName(subdir)).Replace('\\', '/');
AddDirectoryToZip(zipFile, subdir, entry + "/");
}
}
}
}