ZipFile.CreateFromDirectory引发System.IO.IOException:进程无法访问文件X

本文关键字:访问 文件 进程 引发 CreateFromDirectory System IO IOException ZipFile | 更新日期: 2023-09-27 18:00:15

实际上我正在尝试创建一个目录的zip文件,但ZipFile.CreateFromDirectory()给出了以下异常。

System.IO.IOException:进程无法访问该文件PATH_TO_CREATE_ZIP/file.ZIP',因为它正被另一个用户使用过程

以下是它的代码段。:

public void createZipFile(string zipPath, string archiveFileName)
{
    string DirectoryToBeArchive = zipPath + "''" + archiveFileName;
    if (Directory.Exists(DirectoryToBeArchive + ".zip"))
    {
        File.Delete(DirectoryToBeArchive);
        ZipFile.CreateFromDirectory(zipPath, DirectoryToBeArchive + ".zip", CompressionLevel.Fastest, false);
    }
    else
        ZipFile.CreateFromDirectory(zipPath, DirectoryToBeArchive + ".zip", CompressionLevel.Fastest, false);
    Directory.Delete(DirectoryToBeArchive);
}

非常感谢您的帮助。提前感谢。:)

ZipFile.CreateFromDirectory引发System.IO.IOException:进程无法访问文件X

只有得到这个异常才有意义。让我们一步一步地研究您的代码:

createZipFile("C:''Temp", "myZipFile");
public void createZipFile(string zipPath, string archiveFileName)
{
    //DirectoryToBeArchive = "C:''Temp''myZipFile"
    string DirectoryToBeArchive = zipPath + "''" + archiveFileName;
    //Some logical error here, you probably meant to use File.Exists()
    //Basically, as you can't find a directory with name C:''Temp''myZipFile.zip, you always jump into else
    if (Directory.Exists(DirectoryToBeArchive + ".zip"))
    {
        File.Delete(DirectoryToBeArchive);
        ZipFile.CreateFromDirectory(zipPath, DirectoryToBeArchive + ".zip", CompressionLevel.Fastest, false);
    }
    else
        //It will try to overwrite your existing "DirectoryToBeArchive".zip file 
        ZipFile.CreateFromDirectory(zipPath, DirectoryToBeArchive + ".zip", CompressionLevel.Fastest, false);
    //This won't work as well btw, as there probably is no directory 
    //with name C:''Temp''myZipFile
    Directory.Delete(DirectoryToBeArchive);
}

不过,即使删除了文件,也可能会遇到同样的错误。问题是,当你尝试将文件夹C:''Temp压缩到文件C:''Temp''myZipFile.zip中时,你也会尝试压缩文件本身。这实际上就是你得到文件被使用错误的地方。

所以,

  1. 将Directory.Exists()替换为File.Exists()

  2. 在另一个文件夹中压缩

  3. 只是一个友好的警告,如果我是你的话,我会对Directory.Delete()持谨慎态度:)

我的问题是,输出文件夹和压缩文件夹是相同的
移动到不同的文件夹,现在工作正常。

正确代码:

这段代码经过一点修改后对我有效。

string DirectoryToBeArchive = zipPath + "''" + archiveFileName;
            if (File.Exists(DirectoryToBeArchive + ".zip"))
            {
                File.Delete(DirectoryToBeArchive + ".zip");
                ZipFile.CreateFromDirectory(DirectoryToBeArchive, DirectoryToBeArchive + ".zip", CompressionLevel.Fastest, false);
            }
            else
                ZipFile.CreateFromDirectory(DirectoryToBeArchive, DirectoryToBeArchive + ".zip", CompressionLevel.Fastest, false);
            Directory.Delete(DirectoryToBeArchive , true);