如何将多个文件归档到一个 ZIP 文件中?

我正在尝试将文件夹的内容归档到一个 zip 文件中。内容主要是大图像。我正在尝试使用此代码执行此操作:


var folderPicker =

      new Windows.Storage.Pickers.FolderPicker();

folderPicker.SuggestedStartLocation =

      Windows.Storage.Pickers.PickerLocationId.Desktop;

folderPicker.FileTypeFilter.Add("*");

StorageFolder folder = await folderPicker.PickSingleFolderAsync();

if (folder != null)

  {

    StorageFile zipFile = await folder.CreateFileAsync(ThemeName.Text + ".zip",

        Windows.Storage.CreationCollisionOption.GenerateUniqueName);

    Stream themeZipFile = await zipFile.OpenStreamForWriteAsync();

    ZipArchive archive = new ZipArchive(themeZipFile);

    StorageFolder localFolder = ApplicationData.Current.LocalFolder;

    StorageFolder temp = await localFolder.GetFolderAsync("Temp");

    var files = await temp.GetFilesAsync();

    foreach (var item in files)

      {

        archive.CreateEntryFromFile(item.Path, item.Name);

      }

   }

但是,在执行时,我收到一个错误:


IOException: 无法寻找为负的绝对流位置。


现在,当我尝试此代码时:


StorageFolder localFolder = ApplicationData.Current.LocalFolder;

var folderPicker = new Windows.Storage.Pickers.FolderPicker();

folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;

folderPicker.FileTypeFilter.Add("*");

StorageFolder folder = 

    await folderPicker.PickSingleFolderAsync();

if (folder != null)

  {

    StorageFile zipFile =

        await folder.CreateFileAsync(ThemeName.Text + ".zip", Windows.Storage.CreationCollisionOption.GenerateUniqueName);

    await Task.Run(() => ZipFile.CreateFromDirectory(localFolder.Path, zipFile.Path));

  }

我知道我选择的任何文件夹都被拒绝访问!我怎样才能解决这个问题,将几个较大的文件合并到一个档案中?


GCT1015
浏览 206回答 3
3回答

守着星空守着你

如何将多个文件归档到一个 ZIP 文件中?CreateFromDirectory方法将创建带有第二个destinationArchiveFileName 参数的zip 文件。所以你不需要提前创建 zip 文件。您可以使用以下代码直接压缩您的文件夹。if (ZipFolder != null){    // Application now has read/write access to all contents in the picked folder (including other sub-folder contents)    StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", ZipFolder);    await Task.Run(() =>    {        try        {            ZipFile.CreateFromDirectory(ApplicationData.Current.LocalFolder.Path, $"{ZipFolder.Path}\\{Guid.NewGuid()}.zip");            Debug.WriteLine("folder zipped");        }        catch (Exception w)        {            Debug.WriteLine(w);        }    });}

幕布斯7119047

使用此方法,您可以从源目录开始创建 ZIP 文件。这里有一些微软的文档:ZIPFile.CreateFromDirectory你可以在这个命名空间中找到提到的类和方法:System.IO.Compression

子衿沉夜

如果创建临时文件夹来存档整个文件夹是您的解决方案,请尝试以下操作:using System.IO.Compression;var files = System.IO.Directory.EnumerateFiles(string PATH, ".jpeg", System.IO.SearchOption.AllDirectories) foreach (var file in files)   {   File.Copy(file, tempPath + @"\" + System.IO.Path.GetFileName(file));   }ZipFile.CreateFromDirectory(tempPath, zipPath, CompressionLevel.Fastest, true);Directory.Delete(tempPath, true); //delete tempfolder after compress commplete
打开App,查看更多内容
随时随地看视频慕课网APP