Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.IO.Compression.ZipFile UnauthorizedAccessException

Tags:

.net

zip

zipfile

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

}
like image 759
jmac Avatar asked Oct 18 '12 13:10

jmac


3 Answers

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.

like image 181
Brandon Hawbaker Avatar answered Nov 14 '22 06:11

Brandon Hawbaker


The problem can also arises when a folder with the same name as the (output) zip already exists

like image 36
herve Avatar answered Nov 14 '22 05:11

herve


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);
 [...]
like image 24
moskito-x Avatar answered Nov 14 '22 06:11

moskito-x