Search code examples
c#directoryioexceptionzip

ZipFile.CreateFromDirectory throws System.IO.IOException : The process cannot access the file X because it is being used by another process


Actually I'm trying to create zip file of a directory and but the ZipFile.CreateFromDirectory() giving below Exception.

System.IO.IOException : The process cannot access the file PATH_TO_CREATE_ZIP/file.zip' because it is being used by another process.

Following is the Code Snippet for it. :

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);
}

Help Would be Much Appreciated. Thanks in Advance. :)


Solution

  • It only makes sense you get this exception. Let's investigate your code step by step:

    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);
    }
    

    Though, even if you delete the file, you will probably hit same error. The thing is when you try zipping the folder C:\\Temp into the file C:\\Temp\\myZipFile.zip you will also try zipping the file itself. That's actually where you get the file is being used error.

    So,

    1. Replace Directory.Exists() with File.Exists()

    2. Zip in another folder

    3. Just a friendly warning, I'd be cautious with Directory.Delete() if I were you :)