WSK WSK - 1 month ago 28
C# Question

Why sometimes Directory.CreateDirectory Fails?

Here is my code that I am using to extract a zip file making sure the target dir doesn't have any dirty files in it

internal void UnzipProject()
{
if (Directory.Exists(SourceDir))
Directory.Delete(SourceDir, true);

if (File.Exists(CodeZipFile))
{
Directory.CreateDirectory(SourceDir); // fails here
ZipFile.ExtractToDirectory(CodeZipFile, SourceDir);
}
}


Sometime
Directory.CreateDirectory(SourceDir)
fails to create new dir and I get exception on next line but if I step back and retry dir creation, it works. Exactly same pattern is repeated on next execution.

EDIT

Here is the exception that actually is about dir not having been created, I can see the src dir doesn't exist:

System.UnauthorizedAccessException was unhandled
HResult=-2147024891
Message=Access to the path '(...MyPath...)\src\MySolution.sln' is denied.
Source=mscorlib
StackTrace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
at System.IO.Compression.ZipFileExtensions.ExtractToFile(ZipArchiveEntry source, String destinationFileName, Boolean overwrite)
at System.IO.Compression.ZipFileExtensions.ExtractToDirectory(ZipArchive source, String destinationDirectoryName)
at System.IO.Compression.ZipFile.ExtractToDirectory(String sourceArchiveFileName, String destinationDirectoryName, Encoding entryNameEncoding)
at System.IO.Compression.ZipFile.ExtractToDirectory(String sourceArchiveFileName, String destinationDirectoryName)
........

WSK WSK
Answer

Thank you all for helping me resolve this issue. Problem was to create a dir just after calling its delete. In my case deleted dir was empty but probably due to file system delays, it became inaccessible before fully deleting. I am sharing the solution, for others facing same issue:

internal void UnzipProject()
{
    if (Directory.Exists(SourceDir))
    {
        DirectoryInfo di = new DirectoryInfo(SourceDir);

        foreach (FileInfo file in di.GetFiles())
            file.Delete();

        foreach (DirectoryInfo dir in di.GetDirectories())
            dir.Delete(true);
    }

    if (File.Exists(zipFile))
        ZipFile.ExtractToDirectory(zipFile, SourceDir);

    else
    {
        if (Directory.Exists(SourceDir))
            Directory.Delete(SourceDir, true);
    }
}