U ovom vodiču, pokazat ćemo vam kako izdvojiti Zip datoteku u C# kodu. Možete koristiti C# za raspakiranje arhive u svojim aplikacijama. Ovaj kod podržava višestruke zip or archive file formats poput GZip, RAR, TAR, 7Zip i više.
Koraci za izdvajanje Zip datoteke u C#
- Instalirajte paket Aspose.Zip for .NET s NuGet.org
- Uključite prostor imena Aspose.Zip u kod
- Koristite metodu SetLicense za postavljanje licence Aspose.Zip API-ja
- Učitaj ulaznu Zip datoteku u FileStream objekt
- Stvorite novu Archive object iz toka datoteke
- Dohvatite broj datoteka u arhivi i prođite kroz unose arhive
- Ekstrahirajte svaki unos arhive i spremite datoteku na disk
Svaki unos u arhivu sadrži ne samo datoteku, već i naziv datoteke. Koristili smo svojstvo Name da dobijemo naziv datoteke, a zatim izdvojili datoteku s istim nazivom.
Kod za izdvajanje Zip datoteke u C#
using System; | |
using System.IO; | |
using System.Text; | |
//Add reference to Aspose.Zip for .NET API | |
//Use following namespace to extract zip file | |
using Aspose.Zip; | |
namespace ExtractZipFile | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
//Set Aspose license before extracting Zip file | |
//using Aspose.Zip for .NET | |
Aspose.Zip.License AsposeZipLicense = new Aspose.Zip.License(); | |
AsposeZipLicense.SetLicense(@"c:\asposelicense\license.lic"); | |
//Open file from disk using a file stream | |
FileStream ZipFileToBeExtracted = File.Open("ZipFileToBeExtracted.zip", FileMode.Open); | |
//Load Zip file stream to Archive object | |
Archive ZipArchiveToExtract = new Archive(ZipFileToBeExtracted); | |
//Get number of files | |
int NumberOfFileInArchive = ZipArchiveToExtract.Entries.Count; | |
//Loop through the archive for each file | |
for(int FileCounter =0; FileCounter < NumberOfFileInArchive; FileCounter++) | |
{ | |
//Get each zip archive entry and extract the file | |
ArchiveEntry ArchiveFileEntry = ZipArchiveToExtract.Entries[FileCounter]; | |
string NameOfFileInZipEntry = ArchiveFileEntry.Name; | |
ArchiveFileEntry.Extract(NameOfFileInZipEntry); | |
} | |
} | |
} | |
} |
U gornjem kodu koristili smo FileStream za učitavanje Zip archive i zatim spremili ekstrahirane izlazne datoteke na disk. Također možete koristiti ovaj kod u C# za raspakiranje datoteke u memoriji. To može biti od pomoći kada trebate te datoteke dalje u kodu ili aplikaciji, a ne želite ih spremati na disk. Pomoću ovog koda možete jednostavno i brzo izraditi vlastiti C# Zip ekstraktor u svojim aplikacijama ili kao neovisni uslužni program.