Advertisement
kyrathasoft

com_wms_zip.cs contains methods supports zip archive manip

Jun 9th, 2019
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 11.08 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.IO.Compression;
  4. using System.Collections.Generic;
  5. using System.Text;
  6.  
  7. namespace com.wms.zip{
  8.    
  9.     /*
  10.         + https://gist.github.com/kyrathasoft/b001c6c07c13180dbdfba44c500d0171
  11.     */
  12.    
  13.     public class ClassZip{ 
  14.    
  15.         public static bool AddTextFileEntryByUpdatingArchive(string txt_content, string txt_filename, string archive_path){            
  16.             bool succeeded = false;            
  17.             try{
  18.                 using (FileStream zipToOpen = new FileStream(archive_path, FileMode.Open)){
  19.                     using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)){
  20.                         ZipArchiveEntry readmeEntry = archive.CreateEntry(txt_filename);
  21.                         using (StreamWriter writer = new StreamWriter(readmeEntry.Open())){
  22.                             writer.Write(txt_content);
  23.                         }                    
  24.                     }
  25.                 }  
  26.                 succeeded = true;
  27.             }catch{}                        
  28.             return succeeded;
  29.         }
  30.        
  31.         public static bool AddingExistingFileByUpdatingArchive(string filepath, string archive_path){          
  32.             bool succeeded = false;        
  33.             try{
  34.                 using (FileStream zipToOpen = new FileStream(archive_path, FileMode.Open)){
  35.                     using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)){
  36.                         ZipArchiveEntry readmeEntry = archive.CreateEntry(Path.GetFileName(filepath));        
  37.                     }
  38.                 }  
  39.                 succeeded = true;
  40.             }catch{}                                   
  41.             return succeeded;
  42.         }
  43.        
  44.         public static bool CreateZipArchiveFromDirectory(string targetDir){
  45.             bool succeeded = false;
  46.             if(IsValidPath(targetDir, false)){
  47.                 string fileOut = new DirectoryInfo(targetDir).Name + ".zip";           
  48.                 try{
  49.                     string _fileout = fileOut;
  50.                     ZipFile.CreateFromDirectory(targetDir, fileOut);
  51.                     Console.WriteLine("\n Zip archive was successfully created.");
  52.                     succeeded = true;
  53.                 }catch(Exception exWhileZipping){
  54.                     Console.Write("\n {0} + \n {1}", exWhileZipping.Message, targetDir);
  55.                 }
  56.             }else{
  57.                 if(targetDir.Length > 0){
  58.                     Console.Write("\n Invalid path: {0}", targetDir);
  59.                 }
  60.             }  
  61.             return succeeded;
  62.         }
  63.        
  64.         public static int CountEntriesInArchive(string zipPath){            
  65.             int count = 0;
  66.             int cnt = 0;            
  67.             try{
  68.                 using (ZipArchive archive = ZipFile.OpenRead(zipPath)){
  69.                     foreach (ZipArchiveEntry entry in archive.Entries){cnt++;}                  
  70.                 }                
  71.                 count = cnt;
  72.             }catch{}                        
  73.             return count;
  74.         }
  75.        
  76.         public static bool DeleteFileFromArchive(string zipPath, string fileToDelete){
  77.             bool succeeded = false;
  78.             try{
  79.                 using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open)){
  80.                     using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)){
  81.                         foreach(ZipArchiveEntry entry in archive.Entries){
  82.                             if(entry.FullName.Contains(fileToDelete) || entry.FullName == fileToDelete){
  83.                                 entry.Delete();
  84.                                 succeeded = true;              
  85.                             }
  86.                         }                          
  87.                     }
  88.                 }                
  89.             }catch{}
  90.             return succeeded;
  91.         }
  92.        
  93.         public static bool ExtractArchiveToDirectoryWithSilentOverwrite(string zipPath, string extractPath){            
  94.             bool succeeded = false;            
  95.             try{
  96.                 using (ZipArchive archive = ZipFile.OpenRead(zipPath)){
  97.                     foreach (ZipArchiveEntry entry in archive.Entries){
  98.                         entry.ExtractToFile(Path.Combine(extractPath, entry.FullName), true);      
  99.                     }                  
  100.                 }                
  101.                 succeeded = true;
  102.             }catch{}
  103.            
  104.             return succeeded;
  105.         }
  106.        
  107.         public static bool ExtractArchiveToDirectory(string archive, string targetDirectory){
  108.             bool success = false;          
  109.             if(File.Exists(archive)){
  110.                 if(!Directory.Exists(targetDirectory)){
  111.                     try{
  112.                         Directory.CreateDirectory(targetDirectory);
  113.                     }catch(Exception exAttemptingCreateDir){
  114.                         Console.WriteLine("Error while attempting to create directory for zip extraction...");
  115.                         Console.WriteLine(exAttemptingCreateDir.Message);
  116.                     }
  117.                 }
  118.                 try{
  119.                     ZipFile.ExtractToDirectory(archive, targetDirectory);
  120.                 }catch(Exception exWhileExtracting){
  121.                     Console.WriteLine("Error during zip extraction...");
  122.                     Console.WriteLine(exWhileExtracting.Message);
  123.                 }
  124.             }
  125.            
  126.             return success;
  127.         }
  128.        
  129.         public static bool ExtractFileFromArchive(string filename, string zipPath, string extractPath){            
  130.             bool succeeded = false;            
  131.             try{
  132.                 using (ZipArchive archive = ZipFile.OpenRead(zipPath)){
  133.                     foreach (ZipArchiveEntry entry in archive.Entries){
  134.                         string fname = entry.FullName;
  135.                         if(fname.Contains(filename)){                          
  136.                             string destinationPath = Path.GetFullPath(Path.Combine(extractPath, entry.FullName));                            
  137.                             //Console.WriteLine("\n Dest. path: {0}", destinationPath);
  138.                             entry.ExtractToFile(destinationPath);
  139.                         }
  140.                     }
  141.                 }
  142.                 succeeded = true;
  143.             }catch{}
  144.  
  145.             return succeeded;
  146.            
  147.         }
  148.    
  149.         public static bool CompressDirectoryToZipArchive(string targetDirectory, string outputDirectory){
  150.             bool success = false;          
  151.             if(Directory.Exists(targetDirectory)){
  152.                 int subdirs = CountDirectoriesRecursively(targetDirectory);
  153.                 int files = GetDirectoryFileCount(targetDirectory);
  154.                 if((subdirs >= 0) && (files > 0)){
  155.                     try{
  156.                         string dirName = new DirectoryInfo(targetDirectory).Name;
  157.                         try{
  158.                             if(Directory.Exists(outputDirectory)){
  159.                                 dirName = outputDirectory + "\\" + dirName;
  160.                             }
  161.                         }catch{}
  162.                         string fileOut = dirName + ".zip";
  163.                         ZipFile.CreateFromDirectory(targetDirectory, fileOut);
  164.                         success = true;
  165.                     }catch(Exception exWhileTryingToCompressToZip){
  166.                         Console.WriteLine(" Error in CompressDirectoryToZipArchive() method:");
  167.                         Console.WriteLine(" " + exWhileTryingToCompressToZip.Message);
  168.                     }
  169.                 }
  170.             }
  171.            
  172.             return success;
  173.         }
  174.        
  175.         public static int CountDirectoriesRecursively(string targetDirectory){
  176.             int iDirs = 0; //if targetDirectory exists, returns total # of all subdirectories, even nested ones
  177.             if(Directory.Exists(targetDirectory)){
  178.                 iDirs = Directory.GetDirectories(targetDirectory, "*", SearchOption.AllDirectories).Length;
  179.             }
  180.             return iDirs;
  181.         }          
  182.        
  183.         public static int GetDirectoryFileCount(string path){
  184.             int fileCount = 0;
  185.             if(Directory.Exists(path)){
  186.                 fileCount = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Length;
  187.             }
  188.             return fileCount;
  189.         }        
  190.  
  191.         public static List<string> GetFilesContainedInZipArchive(string zipPath){
  192.            
  193.             List<string> files = new List<string>();
  194.             using (ZipArchive archive = ZipFile.OpenRead(zipPath)){
  195.                foreach (ZipArchiveEntry entry in archive.Entries){
  196.                    files.Add(entry.FullName);
  197.                }
  198.             }
  199.            
  200.             return files;
  201.         }
  202.        
  203.         public static string[] GetTopLevelDirFiles(string path){
  204.             string[] files = Directory.GetFiles(path, "*.*", SearchOption.TopDirectoryOnly);
  205.             return files;
  206.         }        
  207.  
  208.         public static bool ClearDirAndSubdirsOfFiles(string targetDirectory) {
  209.             bool succeeded = false;
  210.            
  211.             try{
  212.                 // Process the list of files found in the directory.
  213.                 string [] fileEntries = Directory.GetFiles(targetDirectory);
  214.                 foreach(string fileName in fileEntries)
  215.                     ProcessFile(fileName);
  216.  
  217.                 // Recurse into subdirectories of this directory.
  218.                 string [] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
  219.                 foreach(string subdirectory in subdirectoryEntries){
  220.                     ClearDirAndSubdirsOfFiles(subdirectory);       
  221.                 }
  222.                
  223.                 succeeded = true;
  224.                
  225.             }catch{}
  226.  
  227.             return succeeded;
  228.         }
  229.        
  230.         public static bool IsValidPath(string path, bool allowRelativePaths = false){
  231.             bool isValid = true;
  232.  
  233.             try{
  234.                 string fullPath = Path.GetFullPath(path);
  235.  
  236.                 if (allowRelativePaths){
  237.                     isValid = Path.IsPathRooted(path);
  238.                 }
  239.                 else{
  240.                     string root = Path.GetPathRoot(path);
  241.                     isValid = string.IsNullOrEmpty(root.Trim(new char[] { '\\', '/' })) == false;
  242.                 }
  243.             }
  244.             catch(Exception ex){
  245.                 isValid = false;
  246.                 Console.WriteLine("\n " + ex.Message);
  247.             }
  248.  
  249.             return isValid;
  250.         }        
  251.        
  252.         public static void ProcessDirectory(string targetDirectory)
  253.         {
  254.             // Process the list of files found in the directory.
  255.             string [] fileEntries = Directory.GetFiles(targetDirectory);
  256.             foreach(string fileName in fileEntries)
  257.                 ProcessFile(fileName);
  258.             // Recurse into subdirectories of this directory.
  259.             string [] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
  260.             foreach(string subdirectory in subdirectoryEntries)
  261.                 ProcessDirectory(subdirectory);            
  262.         }        
  263.        
  264.         public static void ProcessFile(string path){           
  265.             FileInfo fi = new FileInfo(path);
  266.             File.Delete(fi.FullName);                      
  267.         }      
  268.  
  269.         public static string SanitizeExtractPath(string p){
  270.             string result = p;
  271.            
  272.             result = Path.GetFullPath(result);
  273.             if (!result.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal)){
  274.                 result += Path.DirectorySeparatorChar;
  275.             }
  276.            
  277.             return p;
  278.         }      
  279.            
  280.         public static bool ZipArchiveContainsThisFile(string _archive, string _filename_in_question){
  281.                 bool result = false;
  282.                 if(!File.Exists(_archive)){
  283.                     //control falls through; false is returned...
  284.                 }else{
  285.                     using(ZipArchive archive = ZipFile.OpenRead(_archive)){
  286.                         foreach(ZipArchiveEntry entry in archive.Entries){
  287.                             string filename = Path.GetFileName(entry.FullName);
  288.                             if(filename == _filename_in_question){
  289.                                 result = true;
  290.                                 break;
  291.                             }
  292.                         }
  293.                     }
  294.                 }
  295.                 return result;
  296.         }            
  297.          
  298.     }      
  299.    
  300. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement