Bunachar Eolais

Zip nó unzip comhaid ag baint úsáide as C# - Comhbhrú agus Dí-chomhbhrú Comhad

Cad é ZIP (Formáid Comhaid)

Is formáid cartlainne comhad é ZIP a thacaíonn le comhbhrú sonraí gan chaill. D’fhéadfadh comhad ZIP aon cheann nó níos mó de chomhaid nó comhadlanna a bheith comhbhrúite. Úsáidtear i ndáiríre iarmhíriú .zip nó .ZIP agus an cineál meán MIME application/zip. Úsáidtear ZIP mar bhun-formáid ag go leor feidhmchlár, de ghnáth faoi ainm difriúil. Nuair a bhraitear tríd an gcóras comhad trí chomhéadan úsáideora, feictear de ghnáth deilbhíní grafaice a léiríonn comhaid ZIP mar cháipéis nó réad eile a thaispeánann zipadóir go soiléir. Tá iarratais iolracha chun comhaid a zipáil (comhbhrú) ann, ag brath ar an gcóras oibriúcháin a úsáideann tú. Agus beagnach gach lá, caithfimid comhaid a zipáil nó a unzipáil agus iad a chur ar sheoladh freastalaí stórála nó ar ardán comhroinnte comhad. Ar ámharaí, is féidir an próiseas seo a uathoibriú ag baint úsáide as Aspose.ZIP API . Ligeann sé duit comhaid a chomhbhrú agus a dhíchomhbhrú gan buairt a bheith agat faoi struchtúr bunúsach na gcomhad. Taispeánann an t-alt seo conas oibriú le comhbhrú comhad aonair agus le comhbhrú ilchomhad. Is féidir an pacáiste Aspose.ZIP a chur le do thionscadal .NET ag baint úsáide as an ordú NuGet seo a leanas:

PM> Install-Package Aspose.Zip

Conas comhad aonair a chomhbhrú le C#

  1. Ar an gcéad dul síos, ní mór dúinn réad de rang FileStream a chruthú don chartlann ZIP amach.
  2. Luchtaigh comhad aonair isteach sa réad FileStream .
  3. Cruthaigh réad den rang Archive .
  4. Cuir an comhad leis an chartlann ag baint úsáide as an modh Archive.CreateEntry ( “FileName”, FileStream).
  5. Cruthaigh an chartlann ZIP ag baint úsáide as an modh Archive.Save (FileStream).
        using (FileStream zipFile = File.Open(dataDir + "CompressSingleFile_out.zip", FileMode.Create))
        {
            //File to be added to archive
            using (FileStream source1 = File.Open(dataDir + "alice29.txt", FileMode.Open, FileAccess.Read))
            {
                    using (var archive = new Archive(new ArchiveEntrySettings()))
                {
                    archive.CreateEntry("alice29.txt", source1);
                    archive.Save(zipFile);
                }
            }
        }

Comhbhrú ilchomhad le C#

Is é an difríocht idir comhbhrú comhad aonair agus ilchomhad ná go gcaithfimid níos mó comhad a luchtú isteach sa FileStream agus iad go léir a chur leis an chartlann ZIP ag baint úsáide as an modh Archive.CreateEntry("FileName", FileStream). Taispeánann an píosa cód thíos conas ilchomhad a chur leis an ZIP ag baint úsáide as FileStream.

        // Create FileStream for output ZIP archive
        using (FileStream zipFile = File.Open("compressed_files.zip", FileMode.Create))
        {
	        // File to be added to archive
	        using (FileStream source1 = File.Open("alice29.txt", FileMode.Open, FileAccess.Read))
	            {
		            // File to be added to archive
		            using (FileStream source2 = File.Open("asyoulike.txt", FileMode.Open, FileAccess.Read))
		        {
			        using (var archive = new Archive())
			            {
				            // Add files to the archive
				            archive.CreateEntry("alice29.txt", source1);
				            archive.CreateEntry("asyoulik3.txt", source2);
				            // ZIP the files
				            archive.Save(zipFile, new ArchiveSaveOptions() { Encoding = Encoding.ASCII, ArchiveComment = "two files are compressed in this archive" });
		            	}
		        }
	        }
        }

Comhbhrú comhad ag baint úsáide as Rang FileInfo

Is féidir comhaid a luchtú freisin ag baint úsáide as an rang FileInfo agus iad a chur leis an chartlann ZIP ar an mbealach céanna le roimhe. Soláthraíonn an rang FileInfo airíonna agus modhanna samplach le haghaidh cruthú, cóipeáil, scriosadh, aistrithe, agus oscailt comhad, agus cabhraíonn sé le cruthú réad FileStream.

    using (FileStream zipFile = File.Open("compressed_files.zip", FileMode.Create))
    {
	    // Files to be added to archive
	    FileInfo fi1 = new FileInfo("alice29.txt");
	    FileInfo fi2 = new FileInfo("fields.c");
	    using (var archive = new Archive())
	        {
		        // Add files to the archive
		        archive.CreateEntry("alice29.txt", fi1);
		        archive.CreateEntry("fields.c", fi2);
		        // Create ZIP archive
		        archive.Save(zipFile, new ArchiveSaveOptions() { Encoding = Encoding.ASCII });
	        }
    }

Stóráil Comhaid i gCartlanna gan Comhbhrú

    //Creates zip archive without compressing files
    using (FileStream zipFile = File.Open(dataDir + "StoreMultipleFilesWithoutCompression_out.zip", FileMode.Create))
    {
    FileInfo fi1 = new FileInfo(dataDir + "alice29.txt");
    FileInfo fi2 = new FileInfo(dataDir + "lcet10.txt");

    using (Archive archive = new Archive(new ArchiveEntrySettings(new StoreCompressionSettings())))
    {
        archive.CreateEntry("alice29.txt", fi1);
        archive.CreateEntry("lcet10.txt", fi2);
        archive.Save(zipFile, new ArchiveSaveOptions() { Encoding = Encoding.ASCII });
    }
    }  

Conas comhaid ZIP a chur i bhfolach le pasfhocal i C#

    using (var archive = new Archive(new ArchiveEntrySettings(encryptionSettings: new TraditionalEncryptionSettings("pass"))))
    {
    archive.CreateEntry("entry_name1.dat", "input_file1.dat");
    archive.CreateEntry("entry_name2.dat", "input_file2.dat");
    archive.Save("result_archive.zip");
    }

Úsáidtear an paraiméadar encryptionSettings chun cartlann ZIP a chosaint le pasfhocal.

Conas comhaid UNZIP a dhíghlasáil le pasfhocal i C#

    using (var archive = new Archive("input_archive.zip", new ArchiveLoadOptions{DecryptionPassword = "pass"}))
    {
    archive.ExtractToDirectory("\\outputDirectory");
    }

Úsáidtear an ArchiveLoadOptions le luach an airí DecryptionPassword chun cartlann ZIP a chosaint le pasfhocal a oscailt. Chun na samplaí iomlána agus na comhaid sonraí a fheiceáil, téigh go https://github.com/aspose-zip/Aspose.ZIP-for-.NET .

Úsáid Comhbhrú LZMA laistigh de Chartlann ZIP

Is algartam an slabhra Lempel–Ziv–Markov (LZMA) é a úsáidtear chun comhbhrú sonraí gan chaill a dhéanamh. Úsáideann LZMA algartam comhbhrú foclaire; tá an sruth comhbhrúite ina shruth giotán. Ligeann comhbhrú LZMA laistigh de chartlann ZIP do choimeádáin ZIP iontrálacha a bhfuil comhbhrú LZMA orthu. Taispeánann an cód thíos cur i bhfeidhm LZMA ag baint úsáide as Aspose.ZIP API .

using (FileStream zipFile = File.Open(dataDir + "LZMACompression_out.zip", FileMode.Create))
{
    using (Archive archive = new Archive(new ArchiveEntrySettings(new LzmaCompressionSettings())))
    {
        archive.CreateEntry("sample.txt", dataDir + "sample.txt");
        archive.Save(zipFile);
    }
}

Úsáid Comhbhrú BZip2 laistigh de Chartlann ZIP

Is clár saor in aisce agus oscailte é bzip2 a úsáideann an algartam Burrows–Wheeler. Ní chomhbhrúann sé ach comhaid aonair agus ní cartlann comhad é. Fuair sé a fhorbairt ó Julian Seward, agus tá sé á chothabháil ag Mark Wielaard agus Micah Snyder. Taispeánann an píosa cód thíos cur i bhfeidhm BZip2 ag baint úsáide as Aspose.ZIP API .

using (FileStream zipFile = File.Open(dataDir + "Bzip2Compression_out.zip", FileMode.Create))
{
    using (Archive archive = new Archive(new ArchiveEntrySettings(new Bzip2CompressionSettings())))
    {
        archive.CreateEntry("sample.txt", dataDir + "sample.txt");
        archive.Save(zipFile);
    }
}

Úsáid Comhbhrú PPMd laistigh de Chartlann ZIP

Is teicníc comhbhrú staitistiúil oiriúnach bunaithe ar mhúnlaíocht comhthéacs agus réamh-mheas é Prediction by Partial Matching (PPM). Úsáideann múnlaí PPM tacar de shiombailí roimhe sa sruth siombailí neamhchomhbhrúite chun an chéad siombail eile sa sruth a thuar. Is féidir algartaim PPM a úsáid freisin chun sonraí a chlúdaigh i ngrúpaí réamh-mheasta i anailís chlúdaigh. Taispeánann an píosa cód thíos cur i bhfeidhm PPMd ag baint úsáide as Aspose.ZIP API .

using (FileStream zipFile = File.Open(dataDir + "PPMdCompression_out.zip", FileMode.Create))
{
    using (Archive archive = new Archive(new ArchiveEntrySettings(new PPMdCompressionSettings())))
    {
        archive.CreateEntry("sample.txt", dataDir + "sample.txt");
        archive.Save(zipFile);
    }
}

Dí-chomhbhrú Cartlann le Comhad Aonair

using (FileStream fs = File.OpenRead(dataDir + "CompressSingleFile_out.zip"))
{
    using (Archive archive = new Archive(fs))
    {
        int percentReady = 0;
        archive.Entries[0].ExtractionProgressed += (s, e) =>
        {
            int percent = (int)((100 * e.ProceededBytes) / ((ArchiveEntry)s).UncompressedSize);
            if (percent > percentReady)
            {
                Console.WriteLine(string.Format("{0}% decompressed", percent));
                percentReady = percent;
            }
        };
        archive.Entries[0].Extract(dataDir + "alice_extracted_out.txt");
    }
}

Dí-chomhbhrú Cartlann le Ilchomhaid

using (FileStream zipFile = File.Open(dataDir + "CompressMultipleFiles_out.zip", FileMode.Open))
{
    StringBuilder sb = new StringBuilder("Entries are: ");
    int percentReady = 0;
    using (Archive archive = new Archive(zipFile,
        new ArchiveLoadOptions()
        {
            EntryListed = (s, e) => { sb.AppendFormat("{0}, ", e.Entry.Name); },
            EntryExtractionProgressed = (s, e) =>
            {
                int percent = (int)((100 * e.ProceededBytes) / ((ArchiveEntry)s).UncompressedSize);
                if (percent > percentReady)
                {
                    Console.WriteLine(string.Format("{0}% compressed", percent)); percentReady = percent;
                }
            }
        }))
    {
        Console.WriteLine(sb.ToString(0, sb.Length - 2));
        using (var extracted = File.Create(dataDir + "alice_extracted_out.txt"))
        {
            using (var decompressed = archive.Entries[0].Open())
            {
                byte[] buffer = new byte[8192];
                int bytesRead;
                while (0 < (bytesRead = decompressed.Read(buffer, 0, buffer.Length)))
                {
                    extracted.Write(buffer, 0, bytesRead);
                }
                // Read from decompressed stream to extracting file.
            }
        }
        percentReady = 0;
        archive.Entries[1].Extract(dataDir + "asyoulik_extracted_out.txt");
    }
}

Dí-bhrú Cartlann Stóráilte gan Comhbhrú

using (FileStream zipFile = File.Open(dataDir + "StoreMultipleFilesWithoutCompression_out.zip", FileMode.Open))
{
    using (Archive archive = new Archive(zipFile))
    {
        using (var extracted = File.Create(dataDir + "alice_extracted_store_out.txt"))
        {
            using (var decompressed = archive.Entries[0].Open())
            {
                byte[] buffer = new byte[8192];
                int bytesRead;
                while (0 < (bytesRead = decompressed.Read(buffer, 0, buffer.Length)))
                {
                    extracted.Write(buffer, 0, bytesRead);
                }
                // Read from decompressed stream to extracting file.
            }
        }

        using (var extracted = File.Create(dataDir + "asyoulik_extracted_store_out.txt"))
        {
            using (var decompressed = archive.Entries[1].Open())
            {
                byte[] buffer = new byte[8192];
                int bytesRead;
                while (0 < (bytesRead = decompressed.Read(buffer, 0, buffer.Length)))
                {
                    extracted.Write(buffer, 0, bytesRead);
                }
                // Read from decompressed stream to extracting file.
            }
        }
    }
}

Le haghaidh na samplaí iomlána agus na gcomhad sonraí, téigh go https://github.com/aspose-zip/Aspose.ZIP-for-.NET .