Read the content of zip folder

Santosh Umarani 81 Reputation points
2020-12-02T07:22:37.077+00:00

Hi All,

I have a zipped folder called 'Uploadfiles.zp'. This folder contains folders like:
5.6/Proj , 5.6/PDS, 13/Proj, 13/PDS

I have to read Uploadfiles.zp folder and check if the folder structure is in the expected format or not.
What is the best way to read the contents of the zipped folder preferably without unzipping?

Kindly waiting for your response.

Thanks,
Santosh

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,011 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,436 Reputation points
    2020-12-02T12:00:46.403+00:00

    Hello @Santosh Umarani ,

    The following reads a .zip file, places folders and files into a container which you can inspect.

    Containers for storing files by folder

    using System;  
    using System.Collections.Generic;  
      
    namespace ExtractFiles  
    {  
    	namespace Classes  
    	{  
    		public class ResultContainer  
    		{  
                /// <summary>  
                /// Folder name for files  
                /// </summary>  
    			public string FolderName {get; set;}  
                /// <summary>  
                /// List of files and sizes  
                /// </summary>  
    			public List<FileContainer> List {get; set;} = new List<FileContainer>();  
    			public override string ToString()  
    			{  
    				return FolderName;  
    			}  
    		}  
    		public class FileContainer  
    		{  
                /// <summary>  
                /// File name  
                /// </summary>  
    			public string Name {get; set;}  
                /// <summary>  
                /// File size  
                /// </summary>  
    			public Int64 Size {get; set;}  
    			public override string ToString()  
    			{  
    				return Name;  
    			}  
    		}  
    	}  
    }  
    

    Code to read zip into a Dictionary (change the namespace to your namespace)

    using System;  
    using System.Collections.Generic;  
    using System.IO;  
    using System.IO.Compression;  
    using System.Linq;  
      
    namespace ExtractFiles.Classes  
    {  
    	namespace Classes  
    	{  
      
    		public class ZipHelpers  
    		{  
                /// <summary>  
                /// Get all file names and contents  
                /// </summary>  
                /// <param name="zippedFile">Valid zip file</param>  
                /// <returns></returns>  
    			public static Dictionary<string, byte[]> GetFiles(byte[] zippedFile)  
    			{  
    				using (var ms = new MemoryStream(zippedFile))  
    				{  
    					using (var archive = new ZipArchive(ms, ZipArchiveMode.Read))  
    					{  
    						return archive.Entries.ToDictionary((zae) =>   
                                zae.FullName, (x) => ReadStream(x.Open()));  
    					}  
    				}  
    			}  
      
    			private static byte[] ReadStream(Stream stream)  
    			{  
    				using (var ms = new MemoryStream())  
    				{  
    					stream.CopyTo(ms);  
    					return ms.ToArray();  
    				}  
    			}  
      
    			private static readonly string[] SizeSuffixes = {"bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"};  
      
    			public static string SizeSuffix(Int64 value, int decimalPlaces = 1)  
    			{  
      
    				if (value < 0)  
    				{  
    					return "-" + SizeSuffix(-value);  
    				}  
      
    				int size = 0;  
    				var dValue = (decimal)value;  
    				while (Math.Round(dValue, decimalPlaces) >= 1000)  
    				{  
    					dValue /= 1024M;  
    					size += 1;  
    				}  
      
    				return string.Format("{0:n" + decimalPlaces + "} {1}", dValue, SizeSuffixes[size]);  
    			}  
    		}  
    	}  
    }  
    

    Implementation

    var containers = new List<ResultContainer>();  
    var newItem = false;  
      
    /*  
     * Change to your zip file name and path  
     */  
    var zipFileName = "SampleZip.zip";  
      
    if (!File.Exists(zipFileName))  
    {  
        return;  
    }  
      
      
    var dictionary = ZipHelpers.GetFiles(File.ReadAllBytes(zipFileName));  
      
    var currentContainer = new ResultContainer();  
      
    foreach (KeyValuePair<string, byte[]> keyValuePair in dictionary)  
    {  
    	var folderName = Path.GetDirectoryName(keyValuePair.Key);  
      
    	if (string.IsNullOrWhiteSpace(folderName))  
    	{  
    		folderName = "(root)";  
    	}  
      
    	currentContainer = containers.FirstOrDefault((item) => item.FolderName == folderName);  
    	if (currentContainer == null)  
    	{  
    		currentContainer = new ResultContainer {FolderName = folderName};  
    		newItem = true;  
    	}  
    	else  
    	{  
    		newItem = false;  
    	}  
      
    	currentContainer.List.Add(new FileContainer()  
    	{  
    		Name = Path.GetFileName(keyValuePair.Key),  
    		Size = keyValuePair.Value.Length  
    	});  
    	if (newItem)  
    	{  
    		containers.Add(currentContainer);  
    	}  
      
    }  
      
      
    foreach (var resultContainer in containers)  
    {  
        Console.WriteLine($"Folder: {resultContainer.FolderName}");  
      
        foreach (var fileContainer in resultContainer.List)  
        {  
            Console.WriteLine($"\t{fileContainer.Name} {ZipHelpers.SizeSuffix(fileContainer.Size)}");  
        }  
      
    }  
    

    Which provides the following in this case in the IDE output window. Dependent on your user interface you can display results in a control or simply inspect the results in code.

    Folder: (root)  
    	App.config 183.0 bytes  
    	Form1.Designer.vb 5.1 KB  
    	Form1.resx 5.6 KB  
    	Form1.vb 5.4 KB  
    	packages.config 148.0 bytes  
    	ReadFileProgress.vbproj 6.5 KB  
    	readme.md 3.7 KB  
    	textfile1 - Copy.txt 76.8 KB  
    	textfile1.txt 7.1 KB  
    	VerifyForm.Designer.vb 3.9 KB  
    	VerifyForm.resx 5.6 KB  
    	VerifyForm.vb 839.0 bytes  
    Folder: bin\Debug  
    	DelegateSimple.exe 35.5 KB  
    	DelegateSimple.exe.config 183.0 bytes  
    	DelegateSimple.pdb 83.5 KB  
    	DelegateSimple.xml 3.4 KB  
    	Microsoft.WindowsAPICodePack.dll 102.5 KB  
    	Microsoft.WindowsAPICodePack.xml 149.4 KB  
    	textfile1.txt 7.1 KB  
    Folder: Classes  
    	Delegates.vb 392.0 bytes  
    	FileOperations.vb 6.0 KB  
    	Person.vb 640.0 bytes  
    	ProgressArgs.vb 910.0 bytes  
    	Verify.vb 430.0 bytes  
    Folder: Modules  
    	DialogHelpers.vb 1.7 KB  
    Folder: My Project  
    	Application.Designer.vb 1.4 KB  
    	Application.myapp 499.0 bytes  
    	AssemblyInfo.vb 1.1 KB  
    	Resources.Designer.vb 3.8 KB  
    	Resources.resx 6.4 KB  
    	Settings.Designer.vb 2.8 KB  
    	Settings.settings 272.0 bytes  
    Folder: obj\Debug  
    	DelegateSimple.exe 35.5 KB  
    	DelegateSimple.Form1.resources 180.0 bytes  
    	DelegateSimple.pdb 83.5 KB  
    	DelegateSimple.Resources.resources 1.8 KB  
    	DelegateSimple.VerifyForm.resources 180.0 bytes  
    	DelegateSimple.xml 3.4 KB  
    	DesignTimeResolveAssemblyReferencesInput.cache 7.5 KB  
    	ReadFileProgress.vbproj.CopyComplete 0.0 bytes  
    	ReadFileProgress.vbproj.CoreCompileInputs.cache 42.0 bytes  
    	ReadFileProgress.vbproj.FileListAbsolute.txt 1.6 KB  
    	ReadFileProgress.vbproj.GenerateResource.cache 1.2 KB  
    	ReadFileProgress.vbprojAssemblyReference.cache 33.9 KB  
    Folder: obj\Debug\TempPE  
    	My Project.Resources.Designer.vb.dll 6.5 KB  
    Folder: Resources  
    	Exit_16x.png 271.0 bytes  
    	ExportFile_16x.png 495.0 bytes  
    	Run_16x.png 233.0 bytes  
    
    1 person found this answer helpful.
    0 comments No comments

  2. Castorix31 85,881 Reputation points
    2020-12-02T07:31:28.19+00:00
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.