Used in the project SharpZipLib compressed when folder, if encountered deep directory, files in the same folder is compressed deeper problem. For example, a compressed file in the current directory program folder (D: \ cx \ code \ program \ bin \ debug \ files), then generate compressed package, need to open access to cx \ code \ program \ bin \ debug \ files You can see the contents. Through practice, disguised implemented a custom archive directory name and directory depth of functionality. Code and description below.
First, I want to compress folders and file paths distributed as follows:
A folder: D: \ cx \ code \ program \ bin \ debug \ files \ Upload1
Folder 2: D: \ cx \ code \ program \ bin \ debug \ files \ Upload2
Folders three: D: \ cx \ code \ program \ bin \ debug \ images \ 00001
Second, the need to generate compressed directory format is:
Archive file
Upload1
...... file file1
Upload2
...... file file1
00001
...... file file1
Third, the main implementation code
To add a compressed folder and content through FastZip, add content to traverse not FastZip add a path through ZipFile and specify the path packet compression.
1, FastZip once add Upload1 and Upload2 directory (Talia files belong to the lower class level directory)
var fastZip = new FastZip
{
Password = "ZipPassword",
CreateEmptyDirectories = true
};
//注意路径最后不要带\ filepath为压缩包路径(如 d:\1.zip) 这里第三个参数为true代表遍历当前目录下的所有目录,第四个参数为过滤文件类型
fastZip.CreateZip(filePath, @"D:\cx\code\program\bin\debug\files", true, "json");
2, the path in the packet generated by the step of accessing a ZipFile compressed file, and updates the file to the specified compression
using (var zipFile = new ZipFile(filePath))
{
zipFile.BeginUpdate();
var picList = FilesHelper.FileSearchAsync(dirPicPath, "*.*", SearchOption.AllDirectories,
x => x.Length > 10);
foreach (var s in picList)
{
//指定新添加的文件在压缩包内的目录路径
zipFile.Add(s, $@"00001\{new FileInfo(s).Name}");
}
zipFile.CommitUpdate();
}
This creates a path specified compressed package archive file.
Attach filter specified folder designated file type code above folders can await retrieval
/// <summary>
/// 检索指定目录下的文件
/// </summary>
/// <param name="directoryPath">检索目录路径</param>
/// <param name="searchFilter">检索文件类型(如*.mp4)</param>
/// <param name="option">检索选项</param>
/// <param name="func">文件过滤器(比如只需要.mp4的文件)</param>
/// <returns></returns>
public static async Task<string[]> FileSearchAsync(string directoryPath, string searchFilter, SearchOption option, Func<string, bool> func)
{
var files = Task.Run(() => Directory.GetFiles(directoryPath, searchFilter, option).Where(func).ToArray());
var s = await files;
return s;
}