c# UnauthorizedAccessException when using ZipArchive but not ZipFile

北城余情 提交于 2019-12-02 07:37:34

问题


I am able to zip files from a specific folder using ZipFile.CreateFromDirectory in the following test code (I only used this code to test how zipping works):

// Where the files are located
string strStartPath = txtTargetFolder.Text;

// Where the zip file will be placed
string strZipPath = @"C:\Users\smelmo\Desktop\testFinish\" + strFileNameRoot + "_" + txtDateRange1.Text.Replace(@"/", "_") + "_" + txtDateRange2.Text.Replace(@"/", "_") + ".zip";

ZipFile.CreateFromDirectory(strStartPath, strZipPath);

However, this zips together ALL of the contents in the folder. I am trying to zip together specific items in the folder using ZipArchive in the following code:

// Where the files are located
string strStartPath = txtTargetFolder.Text;

// Where the zip file will be placed
string strZipPath = @"C:\Users\smelmo\Desktop\testFinish\" + strFileNameRoot + "_" + txtDateRange1.Text.Replace(@"/", "_") + "_" + txtDateRange2.Text.Replace(@"/", "_") + ".zip";

using (ZipArchive archive = ZipFile.OpenRead(strStartPath))
{
    foreach (ZipArchiveEntry entry in archive.Entries)
    {
        if (!(entry.FullName.EndsWith(".TIF", StringComparison.OrdinalIgnoreCase)))
        {
            entry.ExtractToFile(Path.Combine(strZipPath, entry.FullName));
         }
     }
 }

It is giving the error at ZipFile.OpenRead(strStartPath). Why am I able to access the exact folder in the first block of code but not the second? Or is there an easier way to search through a folder and only zip specific items?


回答1:


You are utilizing the Zip libraries wrong

Effectively you are trying to open a directory as if it were a zip file, then loop over the contents of that directory (which again is actually a zip file) and then attempting to extract each member into a different zip file

Here is a working example of what you have described you are trying to do:

string strStartPath = @"PATH TO FILES TO PUT IN ZIP FILE";

string strZipPath = @"PATH TO ZIP FILE";

if (File.Exists(strZipPath))
    File.Delete(strZipPath);

using (ZipArchive archive = ZipFile.Open(strZipPath,  ZipArchiveMode.Create))
{
    foreach (FileInfo file in new DirectoryInfo(strStartPath).GetFiles())
    {
        if (!(file.FullName.EndsWith(".TIF", StringComparison.OrdinalIgnoreCase)))
        { 
            archive.CreateEntryFromFile(Path.Combine(file.Directory.ToString(), file.Name), file.Name);
        }
    }
}

This will take all the root level contents of a folder and put it in the zip file. You will need to implement your own way of getting subfolders and their contents recursively, but that is beyond the scope of this question.

EDIT: Here is a working example with proper folder recursion to select all files even in subdirectories

public void ZipFolder()
{
    string strStartPath = @"PATH TO FILES TO PUT IN ZIP FILE";

    string strZipPath = @"PATH TO ZIP FILE";

    if (File.Exists(strZipPath))
        File.Delete(strZipPath);

    using (ZipArchive archive = ZipFile.Open(strZipPath, ZipArchiveMode.Create))
    {
        foreach (FileInfo file in RecurseDirectory(strStartPath))
        {
            if (!(file.FullName.EndsWith(".TIF", StringComparison.OrdinalIgnoreCase)))
            {
                var destination = Path.Combine(file.DirectoryName, file.Name).Substring(strStartPath.Length + 1);
                archive.CreateEntryFromFile(Path.Combine(file.Directory.ToString(), file.Name), destination);
            }
        }
    }
}

public IEnumerable<FileInfo> RecurseDirectory(string path, List<FileInfo> currentData = null)
{
    if (currentData == null)
        currentData = new List<FileInfo>();   

    var directory = new DirectoryInfo(path);

    foreach (var file in directory.GetFiles())
        currentData.Add(file);

    foreach (var d in directory.GetDirectories())
        RecurseDirectory(d.FullName, currentData);
    return currentData;
}


来源:https://stackoverflow.com/questions/44459876/c-sharp-unauthorizedaccessexception-when-using-ziparchive-but-not-zipfile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!