System.IO.Compression.ZipFile UnauthorizedAccessException

jmac picture jmac · Oct 18, 2012 · Viewed 10.6k times · Source

I'm trying to backup some files using the .NET 4.5 ZipFile class and the CreateFromDirectory(string, string) method. I'm getting an UnauthorizedAccessException - Access Denied. I can successfully read all files in that directory as well as write a file to that directory. So I would think that the permissions are set up properly. Any thoughts on why I'm getting access denied on the ZipFile class?

static void Main(string[] args)
{
    string backupLocation = @"C:\Backups";
    string directoriesToBackup = @"F:\myMedia\myPictures\Our Family\2012\Misc";

    try
    {
        ZipFile.CreateFromDirectory(directoriesToBackup, backupLocation);
    }
    catch (System.UnauthorizedAccessException e) 
    {
        Console.WriteLine(e.Message);
    }

    DirectoryInfo di = new DirectoryInfo(@"F:\myMedia\myPictures\Our Family\2012\Misc");
    File.Create(@"F:\myMedia\myPictures\Our Family\2012\Misc\testCreateFromVs.txt");
    foreach (FileInfo i in di.GetFiles())
    {
        Console.WriteLine(i.Name);
    }

    Console.ReadKey();

}

Answer

moskito-x picture moskito-x · Oct 18, 2012

It seems you have misunderstood something.

backupLocation = @"C:\Backups";

you want to overwrite the directory "C:\Backups" with a file ! That's not allowed! ;-) (Access Denied)

You have to specify the path with file name.
Syntax: CreateFromDirectory(string,string)

public static void CreateFromDirectory(
    string sourceDirectoryName,
    string destinationArchiveFileName
)

Example:

 string startPath = @"c:\example\start";
 string zipPath = @"c:\example\result.zip";
 ZipFile.CreateFromDirectory(startPath, zipPath);
 [...]