Zip-файл с использованием C # - PullRequest
       2

Zip-файл с использованием C #

0 голосов
/ 20 сентября 2010

Я хочу заархивировать один файл "CSV" в Zip-файл, используя C # .Net.Ниже я написал код для создания Zip-файла, используя этот код, я могу создать zip-файл, но после создания извлечения файла «Data1.zip» вручную означает, что извлеченное расширение файла должно быть «.csv», но оно не идет.

        FileStream sourceFile = File.OpenRead(@"C:\Users\Rav\Desktop\rData1.csv");
        FileStream destFile = File.Create(@"C:\Users\Rav\Desktop\Data1.zip");

        GZipStream compStream = new GZipStream(destFile, CompressionMode.Compress,false);

        try
        {
            int theByte = sourceFile.ReadByte();
            while (theByte != -1)
            {
                compStream.WriteByte((byte)theByte);
                theByte = sourceFile.ReadByte();
            }
        }
        finally
        {
            compStream.Dispose();
        }

Ответы [ 6 ]

4 голосов
/ 20 сентября 2010

http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream.aspx

Это сжатие gzip, и, очевидно, оно сжимает только поток, который при распаковке принимает имя архива без расширения .gz. Я не знаю, правда ли я здесь. Вы также можете поэкспериментировать с кодом из MSDN, посмотреть, работает ли он.

Я использовал ZipLib для сжатия zip. Он также поддерживает Bz2, который является хорошим алгоритмом сжатия.

2 голосов
/ 20 сентября 2010

Используйте ICSharpCode.SharpZipLib (вы можете загрузить его) и выполните следующее

       private void CreateZipFile(string l_sFolderToZip)
       {
            FastZip z = new FastZip();
            z.CreateEmptyDirectories = true;
            z.CreateZip(l_sFolderToZip + ".zip", l_sFolderToZip, true, "");

            if (Directory.Exists(l_sFolderToZip))
                Directory.Delete(l_sFolderToZip, true);   

      }



        private void ExtractFromZip(string l_sFolderToExtract)
        {
            string l_sZipPath ="ur folder path" + ".zip";
            string l_sDestPath = "ur location" + l_sFolderToExtract;

            FastZip z = new FastZip();
            z.CreateEmptyDirectories = true;
            z.ExtractZip(l_sZipPath, l_sDestPath, "");

            if (File.Exists(l_sZipPath))
                File.Delete(l_sZipPath);
        }

Надеюсь, это поможет ...

2 голосов
/ 20 сентября 2010

Используйте одну из этих библиотек: http://www.icsharpcode.net/opensource/sharpziplib/ http://dotnetzip.codeplex.com/

Я предпочитаю #ziplib, но оба хорошо документированы и широко распространены.

1 голос
/ 18 августа 2015

Взгляните на библиотеку FileSelectionManager здесь: www.fileselectionmanager.com

Сначала вам нужно добавить DLL File Manager Manager в ваш проект

Вотпример для архивирования:

class Program
{
    static void Main(string[] args)
    {
        String directory =  @"C:\images";
        String destinationDiretory =  @"c:\zip_files";
        String zipFileName =  "container.zip";        
        Boolean recursive =  true;
        Boolean overWrite =  true;
        String condition =  "Name Contains \"uni\"";
        FSM FSManager =  new FSM();

        /* creates zipped file containing selected files */ 
        FSManager.Zip(directory,recursive,condition,destinationDirectory,zipFileName,overWrite);

        Console.WriteLine("Involved Files: {0} - Affected Files: {1} ",
        FSManager.InvolvedFiles,
        FSManager.AffectedFiles);

        foreach(FileInfo file in FSManager.SelectedFiles)
        {
            Console.WriteLine("{0} - {1} - {2} - {3} - {4}  Bytes",
            file.DirectoryName,
            file.Name,
            file.Extension,
            file.CreationTime,
            file.Length);
        }
    }
}

Вот пример для распаковки:

class Program
{
    static void Main(string[] args)
    {
        String destinationDiretory =  @"c:\zip_files";
        String zipFileName =  "container.zip";        
        Boolean unZipWithDirectoryStructure =  true;
        FSM FSManager =  new FSM();

        /* Unzips files with or without their directory structure */ 
        FSManager.Unzip(zipFileName,
                  destinationDirectory,
                  unZipWithDirectoryStructure);

      }
}

Надеюсь, это поможет.

1 голос
/ 23 декабря 2013

Начиная с .NET Framework 4.5, вы можете использовать встроенный класс ZipFile (в пространстве имен System.IO.Compression).

public void ZipFiles(string[] filePaths, string zipFilePath)
{

    ZipArchive zipArchive = ZipFile.Open(zipFilePath, ZipArchiveMode.Create);
    foreach (string file in filePaths)
    {
        zipArchive.CreateEntryFromFile(file, Path.GetFileName(file), CompressionLevel.Optimal);
    }
    zipArchive.Dispose();

}
0 голосов
/ 19 августа 2015

Я использую dse fileselectionmanager для сжатия и распаковки файлов и папок, в моем проекте это работало должным образом.Вы можете увидеть пример в своей сети http://www.fileselectionmanager.com/#Zipping и Разархивировать файлы и документацию http://www.fileselectionmanager.com/file_selection_manager_documentation

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...