[英]How to archive several files in one ZIP file?
我试图将文件夹的内容存档为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));
}
我得到的访问被拒绝到我选择的任何文件夹! 如何解决这个问题,将几个较大的文件合并到一个存档中?
使用此方法,您可以从源目录开始创建ZIP文件。 这里有一些Microsoft的文档: 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
如何在一个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);
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.