Windows Forms: List all file names in Zip file in C#
By FoxLearn 3/20/2020 7:05:09 PM 5.44K
This post shows you how to list all file names in zip file in c# .net windows forms application.
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.
To list zip file contents in c#, you need to add a reference to WindowsBase.dll, then add code to handle your windows forms application as shown below.
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.IO; using System.IO.Packaging; using System.Linq; using System.Reflection; using System.Windows.Forms; namespace AppSource { public partial class Form6 : Form { public Form6() { InitializeComponent(); } 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; } 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; } } } } }
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.
Click the Zip file button to read a zip file, then you can list the contents of a .zip folder in c# to listbox control.
Categories
Popular Posts
Visual Studio: Auto increment version
04/01/2024
What is ARM architecture?
04/01/2024
What Are RESTful Web Services?
02/19/2024