在 C# 中解压缩 ZIP 文件时出现 UnauthorizedAccessException

问题描述 投票:0回答:0

我有以下解压缩 zip 文件的代码,碰巧目标目录是只读的。 ExractToFile 抛出异常......有什么想法吗? zip文件的内容是一个目录及其下的文件。

ZipArchive 来自“using System.IO.Compression;”

    public void UnzipFile(string zipFilePath, string destinationDir)
    {
        using (Log.VerboseCall())
        {
            if (String.IsNullOrEmpty(zipFilePath))
            {
                throw new ArgumentException("zipFilePath is invalid.");
            }

            if (String.IsNullOrEmpty(destinationDir))
            {
                throw new ArgumentException("destinationDir is invalid.");
            }

            if (!Directory.Exists(destinationDir))
            {
                Directory.CreateDirectory(destinationDir);
            }

            SetFullAccessPermissionsForEveryone(destinationDir);

            if (!File.Exists(zipFilePath))
            {
                throw new ArgumentException(String.Format("zipFilePath does not exist: {0}", zipFilePath));
            }

            try
            {
                using (ZipArchive archive = ZipFile.OpenRead(zipFilePath))
                {
                    int count = archive.Entries.Count;
                    var root = archive.Entries[0]?.FullName;
                    int counter = 0;

                    foreach (ZipArchiveEntry entry in archive.Entries)
                    {
                        var newName = entry.FullName.Substring(root.Length);
                        string path = Path.Combine(destinationDir, newName);

                        if (!Directory.Exists(path))
                        {
                            // it is a file
                            FileAttributes attr = File.GetAttributes(path);
                            File.SetAttributes(path, attr | ~FileAttributes.ReadOnly);
                        }
                        else
                        {
                            // it is a folder
                            DirectoryInfo ss = new DirectoryInfo(path);
                            ss.Attributes &= ~FileAttributes.ReadOnly;
                        }

                        entry.ExtractToFile(path, true);

                        counter++;
                        int percent = counter * 100 / count;
                        UpdateProgress(percent, false, (string)newName);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Verbose(ex);
            }
        }
    }

我没有手动从目标文件夹中删除只读,因为它可能发生在任何目标计算机上...

c# unzip
© www.soinside.com 2019 - 2024. All rights reserved.