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();
}
In my case I was trying to create the target directory before I started to zip the file there, but was creating the target directory as the name of the zip file, so because the empty zip file already existed (as a directory), I got the same error.
The problem can also arises when a folder with the same name as the (output) zip already exists
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);
 [...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With