How to List all file names in Zip file in C#
By FoxLearn 7/19/2024 2:14:09 AM 5.8K
To list all file names in a zip file in C# using Windows Forms, you can use the System.IO.Packaging
namespace from the WindowsBase
assembly.
Here's a step-by-step guide on how to achieve this:
To play the demo, we will design a simple UI that allows you to select a zip file, then get file list of files contained in a zip file and show it in the listbox control.
Ensure you have included the necessary namespace:
using System.IO.Packaging;
To list zip file contents in c#, you need to add a reference to WindowsBase.dll, then create methods to list the file names in the zip file as shown below.
public List<string> GetFiles(ZipPackage zp) { List<string> list = new List<string>(); try { var zipArchiveProperty = zp.GetType().GetField("_zipArchive", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Instance); var zipArchive = zipArchiveProperty.GetValue(zp); var zipFileInfoDictionaryProperty = zipArchive.GetType().GetProperty("ZipFileInfoDictionary", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Instance); var zipFileInfoDictionary = zipFileInfoDictionaryProperty.GetValue(zipArchive, null) as Hashtable; var query = from DictionaryEntry de in zipFileInfoDictionary select de.Key.ToString(); list = query.ToList(); } catch (Exception ex) { throw ex; } return list; } private List<string> GetFileListFromZipFile(FileInfo zipFileName) { List<string> list = new List<string>(); try { var zipPackagep = ZipPackage.Open(zipFileName.FullName, FileMode.Open, FileAccess.Read, FileShare.Read) as ZipPackage; list = GetFiles(zipPackagep); } catch (Exception ex) { throw ex; } return list; }
You need to write the following two methods: GetFiles() and GetFileListFromZipFile(). These two methods will return to you a List<string> containing all the files contained in the Zip archive.
Add a ListBox (listBox1
), and a Button (btnZipFile
) to your Windows Form, then handle the button click event to select the zip file.
private void btnZipFile_Click(object sender, EventArgs e) { using (OpenFileDialog dialog = new OpenFileDialog()) { if (dialog.ShowDialog() == DialogResult.OK) { var fi = new FileInfo(dialog.FileName); var files = GetFileListFromZipFile(fi); listBox1.DataSource = files; } } }
This code allows users to select a zip file using a file dialog, and then displays all the file names contained within the zip file in a ListBox using the System.IO.Packaging
namespace.
Click the Zip file button to read your zip file, then you can list the contents of a *.zip folder in c#, then display it to the listbox control.