通用Windows平台ZipFile.CreateFromDirectory创建空的ZIP文件

本文关键字:ZIP 文件 创建 CreateFromDirectory Windows 平台 ZipFile 通用 | 更新日期: 2023-09-27 18:22:41

我在压缩现有目录时遇到问题。当我试图压缩现有目录时,我总是得到一个空的zip文件。我的代码基于MSDN中的这个示例。调试应用程序时没有异常。

我的代码:

private async void PickFolderToCompressButton_Click(object sender, RoutedEventArgs e)
{
    // Clear previous returned folder name, if it exists, between iterations of this scenario
    OutputTextBlock.Text = "";
    FolderPicker folderPicker = new FolderPicker();
    folderPicker.SuggestedStartLocation = PickerLocationId.Desktop;
    folderPicker.FileTypeFilter.Add(".dll");
    folderPicker.FileTypeFilter.Add(".json");
    folderPicker.FileTypeFilter.Add(".xml");
    folderPicker.FileTypeFilter.Add(".pdb");
    StorageFolder folder = await folderPicker.PickSingleFolderAsync();
    if (folder != null)
    {
        // Application now has read/write access to all contents in the picked folder (including other sub-folder contents)
        StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", folder);
        OutputTextBlock.Text = $"Picked folder: {folder.Name}";
        var files  = await folder.GetFilesAsync();
        foreach (var file in files)
        {
            OutputTextBlock.Text += $"'n {file.Name}";
        }
        await Task.Run(() =>
        {
            try
            {
                ZipFile.CreateFromDirectory(folder.Path, $"{folder.Path}''{Guid.NewGuid()}.zip",
                    CompressionLevel.NoCompression, true);
                Debug.WriteLine("folder zipped");
            }
            catch (Exception w)
            {
                Debug.WriteLine(w);
            }
        });
    }
    else
    {
        OutputTextBlock.Text = "Operation cancelled.";
    }
}

Zip文件已创建,但它始终为空。源文件夹中有许多文件。

通用Windows平台ZipFile.CreateFromDirectory创建空的ZIP文件

我们发现这可能是由文件系统api的.NET Core实现引起的。

目前的解决方法是首先将您的文件夹压缩到windows运行时应用程序的本地数据文件夹中,在使用zipfile类时,从该文件夹中读取可以生成预期的结果。

您可以参考MSDN上的相关文章。

zip文件库只支持压缩回应用程序本地文件夹。如果您拥有来自其他文件夹的权限令牌,则可能需要直接压缩。writeZip函数还可以用于从其他地方添加单独的文件。

        public async void Backup(StorageFolder source, StorageFolder destination)
        {
            var zipFile = await destination.CreateFileAsync("backup.zip",
               CreationCollisionOption.ReplaceExisting);
            var zipToCreate = await zipFile.OpenStreamForWriteAsync();
            using (var archive = new ZipArchive(zipToCreate, ZipArchiveMode.Update))
            {
                var parent = source.Path.Replace(source.Name, "");
                await RecursiveZip(source, archive, parent);
            }
        }
        private async Task RecursiveZip(StorageFolder sourceFolder, ZipArchive archive, string sourceFolderPath)
        {
            var files = await sourceFolder.GetFilesAsync();
            foreach (var file in files)
            {
                await WriteZip(file, archive, sourceFolderPath);
            }
            var subFolders = await sourceFolder.GetFoldersAsync();
            foreach (var subfolder in subFolders)
            {
                await RecursiveZip(subfolder, archive, sourceFolderPath);
            }
        }
        private async Task WriteZip(StorageFile file, ZipArchive archive, string sourceFolderPath)
        {
            var entryName = file.Path.Replace(sourceFolderPath, "");
            var readmeEntry = archive.CreateEntry(entryName, CompressionLevel.Optimal);
            var reader = await file.OpenStreamForReadAsync();
            using (var entryStream = readmeEntry.Open())
            {
                await reader.CopyToAsync(entryStream);
            }
        }