Using ZipFile


Hi Everyone,

I have started programming in C# for couple of days, I was trying to use Zipfile class, but I faced many issues. So I felt the obligation to share them with you, and how to solve it.

1. The reference wasn't added by default, so you need to add the references System.IO.Compression and System.IO.Compression.FileSystem.

2. Using the class ZipFele I had a problem with the access. I always received the access denied error because the clas Zipfile used the whole path including the name and the extension.
ZipFile.ExtractToDirectory(compressfiles[i], extractPath);

Below the code and a video with the explanation:


Reference:
https://msdn.microsoft.com/en-us/library/system.io.compression.zipfile_methods(v=vs.110).aspx 

Programs:

private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Hello");
            string startPath = @"C:\Users\\Desktop\Test";
            string zipPath = "C:\\Users\\Desktop\\Test";
            string extractPath = "C:\\Users\\Desktop\\Test\\extract";
       
            string[] compressfiles = Directory.GetFiles("C:\\Users\\Desktop\\Test", @"*.zip");

            for (int i = 0; i < compressfiles.Length; i++)
            {
                //compressfiles[i] = Path.GetFileName(compressfiles[i]);
                MessageBox.Show(compressfiles[i]);
                ZipFile.ExtractToDirectory(compressfiles[i], extractPath); // you need to use the whole path including the name of the file and
                /// the extension.
            }
            ///ZipFile.CreateFromDirectory(startPath, zipPath);
           /// using (ZipArchive archive = ZipFile.OpenRead(zipPath))
            ///{
            ///ZipFile.ExtractToDirectory(zipPath, extractPath); /// if doesn't work please add the reference System.IO.Compression.FileSystem
            ///}
        }

Comments

  1. using System;
    using System.IO;

    public class Example
    {
    public static void Main()
    {
    string filePath = @".\ROFile.txt";
    if (! File.Exists(filePath))
    File.Create(filePath);
    // Keep existing attributes, and set ReadOnly attribute.
    File.SetAttributes(filePath,
    (new FileInfo(filePath)).Attributes | FileAttributes.ReadOnly);

    StreamWriter sw = null;
    try {
    sw = new StreamWriter(filePath);
    sw.Write("Test");
    }
    catch (UnauthorizedAccessException) {
    FileAttributes attr = (new FileInfo(filePath)).Attributes;
    Console.Write("UnAuthorizedAccessException: Unable to access file. ");
    if ((attr & FileAttributes.ReadOnly) > 0)
    Console.Write("The file is read-only.");
    }
    finally {
    if (sw != null) sw.Close();
    }
    }
    }
    // The example displays the following output:
    // UnAuthorizedAccessException: Unable to access file. The file is read-only.

    ReplyDelete

Post a Comment

Popular posts from this blog

SFTP download - upload

FTP - Server in C# FtpWebRequest