Solved

Trying to zip a folder in C# using System.IO.Packaging

Posted on 2010-09-09
5
2,078 Views
Last Modified: 2012-05-10
I can get single files to zip into a specified folder just fine, but I want to benchmark a couple different options (using DotNetZip, System.IO.Packaging, and System.IO.Compression.GZipStream). It would make it a lot easier to be able to add a folder.

My program keeps failing at this line:
using (Package zip = System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate))

With this Error:
Access to the path '**Folder Path**' is denied.

 Part of my code is below:
string[] filePaths = Directory.GetFiles(fileToAdd, "*", SearchOption.AllDirectories);



            foreach (string file in filePaths)

            {

                // FAILS ON THE NEXT LINE

                // Error: "Access to the path '** Folder Path**' is denied."



                using (Package zip = System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate))

                {

                    string destFilename = ".\\" + Path.GetFileName(fileToAdd);

                    Uri uri = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));

                    if (zip.PartExists(uri))

                    {

                        zip.DeletePart(uri);

                    }

                    PackagePart part = zip.CreatePart(uri, "", CompressionOption.Normal);

                    using (FileStream fileStream = new FileStream(fileToAdd, FileMode.Open, FileAccess.ReadWrite))

                    {

                        using (Stream dest = part.GetStream())

                        {

                            CopyStream(fileStream, dest);

                            dest.Close();

                        }

                        fileStream.Close();

                    }

                }

            } 





        private static void CopyStream(FileStream inputStream, Stream outputStream)

        {

            long bufferSize = inputStream.Length < BUFFER_SIZE ? inputStream.Length : BUFFER_SIZE;

            byte[] buffer = new byte[bufferSize];

            int bytesRead = 0;

            long bytesWritten = 0;

            while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) != 0)

            {

                outputStream.Write(buffer, 0, bytesRead);

                bytesWritten += bufferSize;

            }

        }

Open in new window

0
Comment
Question by:bickes0724
  • 3
  • 2
5 Comments
 
LVL 96

Expert Comment

by:Bob Learned
ID: 33636804
I don't understand your zip process.  You have a loop for each file, and you open and close the .zip file.  Also, what file path are you using with 'zipFileName', and should you have access within the security context for the running application?
0
 

Author Comment

by:bickes0724
ID: 33636961
Here is more code and the paths you asked for. I am not sure why I am closing the connections in the previous code. Honestly, I haven't been able to debug that far yet because of the error. Below is code that actually works as expected.


private void Button_Click(object sender, RoutedEventArgs e)
        {  
          // AddFileToZip(@"C:\Users\bickes\Desktop\NewZipFolder.zip", @"C:\Users\bickes\Desktop\TestZip", true);
            AddFileToZip(@"C:\Users\bickes\Desktop\NewZipFolder.zip", @"C:\Users\bickes\Desktop\FM.Portal.SetFacilities\FM.Portal.SetFacilities.sln", false);
            AddFileToZip(@"C:\Users\bickes\Desktop\NewZipFolder.zip", @"C:\Users\bickes\Desktop\FM.Portal.SetFacilities\FM.Portal.SetFacilities.csproj", false);
        }

        private const long BUFFER_SIZE = 4096;

        private static void AddFileToZip(string zipFilename, string fileToAdd, bool IsFolder)
        {
            if (IsFolder == false)
            {
                using (Package zip = System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate))
                {
                    string destFilename = ".\\" + Path.GetFileName(fileToAdd);
                    Uri uri = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));
                    if (zip.PartExists(uri))
                    {
                        zip.DeletePart(uri);
                    }
                    PackagePart part = zip.CreatePart(uri, "", CompressionOption.Normal);
                    using (FileStream fileStream = new FileStream(fileToAdd, FileMode.Open, FileAccess.Read))
                    {
                        using (Stream dest = part.GetStream())
                        {
                            CopyStream(fileStream, dest);
                            dest.Close();
                        }
                        fileStream.Close();
                    }
                }
                return;
            }
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 33640793
1) What kind of application is this?  Windows Forms?  Windows Service?

2) Where does it run from?

3) What is the operating system (it looks like Vista or Windows 7)?

4) For Vista or Windows 7, do you have UAC turned on?
0
 

Author Comment

by:bickes0724
ID: 33646430
I went a different route. Thank you for all your help. I wasn't very clear when I was explaining myself yesterday. I have posted my working code below to help anyone else...
0
 

Accepted Solution

by:
bickes0724 earned 0 total points
ID: 33646436

private static void PackageCompress(string destinationFile, string sourceFile)

        {

            if (File.Exists(sourceFile))

            {

                using (Package zip = Package.Open(destinationFile, FileMode.OpenOrCreate))

                {

                    string destFilename = ".\\" + Path.GetFileName(sourceFile);

                    Uri uri = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));

                    if (zip.PartExists(uri))

                    {

                        zip.DeletePart(uri);

                    }

                    PackagePart part = zip.CreatePart(uri, "", CompressionOption.Normal);

                    using (FileStream fileStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read))

                    {

                        using (Stream dest = part.GetStream())

                        {

                            CompressCopyStream(fileStream, dest);

                            dest.Close();

                        }

                        //fileStream.Close();

                    }

                }                

            }

            

        }

        

        public static void PackageDecompress(string destinationFile, string sourceFile)

        {



            using (Package package__1 = Package.Open(sourceFile, FileMode.Open, FileAccess.Read))

            {

                foreach (PackagePart part in package__1.GetParts())

                {

                    Stream input = part.GetStream();

                    FileStream output = new FileStream(destinationFile + part.Uri.ToString(), FileMode.Create, FileAccess.Write);

                    DecompressCopyStream(input, output);



                    input.Close();

                    output.Close();

                }

                

            }

        }

Open in new window

0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Need help on C# Linq query on object 6 53
Error on Add method 1 38
Want to create a userform that looks like the image provided 10 44
Crystal reports vb.net 2 16
It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …

895 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now