Advertisement
kyrathasoft

zipping files to result.zip or extracting files from archive

Jun 2nd, 2019
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 9.15 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.IO.Compression;
  4.  
  5. namespace ConsoleApplication {
  6.    
  7.     /*
  8.     links to online source code listing: last updated 6/4/2019
  9.       + https://gist.github.com/kyrathasoft/bdebc9ad97941e35abdde146bbf2d73b
  10.       + https://pastebin.com/QYFZXEkq
  11.     */
  12.  
  13.     class Program{
  14.        
  15.         static bool blnExit = false;
  16.         static string startPath = @".\start";
  17.         static string zipPath = @".\result.zip";
  18.         static string extractPath = @".\extract";
  19.  
  20.  
  21.         static void Main(string[] args){
  22.            
  23.             ShowTitle();
  24.             if(Init()){
  25.                 Console.WriteLine("\n Program initialization succeeded.");
  26.                 /* Because Init() succeeded, we know that:
  27.                    (1) there's a /start subdir with at least one file
  28.                    (2) there's NOT a result.zip file in the EXE's dir
  29.                    (3) there's an /extract subdir that is empty
  30.                 */
  31.                 while(!blnExit){
  32.                     BuildMenu();
  33.                 }
  34.                
  35.                 Console.WriteLine("\n Program exits...\n");
  36.             }
  37.         }
  38.        
  39.         public static void BuildMenu(){
  40.             Console.WriteLine("\n\n     Menu:");
  41.             if(StartSubdirExistsWithOneOrMoreFiles() && ZipArchiveResultFileDoesntExist()){
  42.                 Console.WriteLine("       (Z)ip start subdir files to result.zip");
  43.             }
  44.             if(File.Exists("result.zip")){
  45.                 Console.WriteLine("      (E)xtract result.zip to .\\extract subdirectory");
  46.                 Console.WriteLine("       Extract (O)nly 'Program.cs to .\\extract sudirectory");
  47.                 Console.WriteLine("       (D)oes file 'MainForm.cs' exist in archive?");
  48.                 if(!ZipArchiveContainsThisFile("result.zip", "MyNameIs.txt")){
  49.                     Console.WriteLine("       D(y)namically add name/b-day to archive as entry 'MyNameIs.txt'");
  50.                 }
  51.             }
  52.            
  53.             Console.WriteLine("       E(x)it Program");
  54.             Console.Write("           Your selection > ");
  55.             ConsoleKeyInfo cki = Console.ReadKey();
  56.             switch(cki.Key){                    
  57.                 case ConsoleKey.Z:
  58.                     ZipFile.CreateFromDirectory(startPath, zipPath);
  59.                     SeeIfExtractDirExistsAndDeleteItsFiles();                
  60.                     break;
  61.                 case ConsoleKey.D:
  62.                     if(ZipArchiveContainsThisFile("result.zip", "MainForm.cs")){
  63.                         Console.WriteLine("\n          Yes, 'MainForm.cs' is contained in result.zip.");
  64.                     }else{
  65.                         Console.WriteLine("\n          No, the program didn't find 'MainForm.cs' in result.zip.");
  66.                     }
  67.                     break;
  68.                 case ConsoleKey.E:
  69.                     extractPath = SanitizeExtractPath(extractPath);
  70.                     ZipFile.ExtractToDirectory(zipPath, extractPath);
  71.                     SeeIfZippedArchiveExistsIfSoDelete();                
  72.                     break;
  73.                 case ConsoleKey.O:
  74.                     extractPath = SanitizeExtractPath(extractPath);
  75.                     using (ZipArchive archive = ZipFile.OpenRead(zipPath)){
  76.                         foreach (ZipArchiveEntry entry in archive.Entries){
  77.                             string fname = entry.FullName;
  78.                             if(fname.Contains("Program.cs")){
  79.                                 //Console.WriteLine("\n Found 'Program.cs'...");                            
  80.                                 string destinationPath = Path.GetFullPath(Path.Combine(extractPath, entry.FullName));                            
  81.                                 Console.WriteLine("\n Dest. path: {0}", destinationPath);
  82.                                 entry.ExtractToFile(destinationPath);
  83.                             }
  84.                         }
  85.                     }                
  86.                     break;
  87.                 case ConsoleKey.Y:
  88.                     using (FileStream zipToOpen = new FileStream(@".\result.zip", FileMode.Open))
  89.                     {
  90.                         using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
  91.                         {
  92.                             ZipArchiveEntry readmeEntry = archive.CreateEntry("MyNameIs.txt");
  93.                             using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
  94.                             {
  95.                                     writer.WriteLine("My name is Bryan Miller.");
  96.                                     writer.WriteLine("The date: {0}", DateTime.Now.ToString());
  97.                             }
  98.                             Console.WriteLine("\n       Successfully added 'MyNameIs.txt' to 'result.zip'");
  99.                         }
  100.                     }              
  101.                     break;
  102.                 default:
  103.                     blnExit = true;
  104.                     break;
  105.             }
  106.         }
  107.        
  108.         public static bool Init(){
  109.             bool success = false;
  110.             if(SeeIfZippedArchiveExistsIfSoDelete()){
  111.                 if(SeeIfExtractDirExistsAndDeleteItsFiles()){
  112.                     if(SeeIfStartDirExistsAndContainsFilesToBeZipped()){
  113.                         success = true;
  114.                     }
  115.                 }
  116.             }
  117.        
  118.             return success;
  119.         }
  120.        
  121.         public static string SanitizeExtractPath(string p){
  122.             string result = p;
  123.            
  124.             result = Path.GetFullPath(result);
  125.             if (!result.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal)){
  126.                 result += Path.DirectorySeparatorChar;
  127.             }
  128.            
  129.             return p;
  130.         }
  131.        
  132.         public static bool ZipArchiveResultFileDoesntExist(){
  133.             bool result = false;
  134.             if(!File.Exists("result.zip")){ result = true;}
  135.             return result;
  136.         }
  137.        
  138.         public static bool ZipArchiveContainsThisFile(string _archive, string _filename_in_question){
  139.                 bool result = false;
  140.                 if(!File.Exists(_archive)){
  141.                     //control falls through; false is returned...
  142.                 }else{
  143.                     using(ZipArchive archive = ZipFile.OpenRead(_archive)){
  144.                         foreach(ZipArchiveEntry entry in archive.Entries){
  145.                             string filename = Path.GetFileName(entry.FullName);
  146.                             if(filename == _filename_in_question){
  147.                                 result = true;
  148.                                 break;
  149.                             }
  150.                         }
  151.                     }
  152.                 }
  153.                 return result;
  154.         }
  155.        
  156.         public static bool StartSubdirExistsWithOneOrMoreFiles(){
  157.             bool result = false;
  158.            
  159.             if(Directory.Exists(@".\start")){
  160.                 string[] files = Directory.GetFiles(@".\start", "*.*", SearchOption.TopDirectoryOnly);
  161.                 if(files.Length > 0){
  162.                     result = true;
  163.                 }
  164.             }
  165.            
  166.             return result;
  167.         }
  168.        
  169.         public static bool SeeIfZippedArchiveExistsIfSoDelete(){
  170.             bool success = false;
  171.             if(File.Exists("result.zip")){
  172.                 try{
  173.                     File.Delete("result.zip");
  174.                     success = true;
  175.                 }catch{
  176.                     Console.WriteLine("\n Unable to delete result.zip during initialization.");
  177.                 }
  178.             }else{ success = true; }    
  179.             return success;
  180.         }
  181.        
  182.         public static bool SeeIfExtractDirExistsAndDeleteItsFiles(){
  183.             bool success = false;
  184.             if(Directory.Exists(@".\extract")){
  185.                 string[] files = Directory.GetFiles(@".\extract", "*.*", SearchOption.TopDirectoryOnly);
  186.                 if(files.Length > 0){
  187.                     try{
  188.                         for(int i=0; i < files.Length; i++){
  189.                             File.Delete(files[i]);
  190.                         }
  191.                         success = true;
  192.                     }catch{
  193.                         Console.WriteLine("\n Unable to delete files in .\\extract during initialization.");
  194.                     }
  195.                 }else{ success = true; }
  196.             }else{
  197.                 Directory.CreateDirectory(@".\extract");
  198.                 success = true;
  199.             }  
  200.             return success;
  201.         }
  202.        
  203.         public static bool SeeIfStartDirExistsAndContainsFilesToBeZipped(){
  204.             bool success = false;
  205.             if(!Directory.Exists(@".\start")){
  206.                 Console.WriteLine("\n Missing .\\start subdirectory with files to be zipped.");
  207.                 Console.WriteLine(" Program will terminate.\n");
  208.             }else{
  209.                 //directory exists, but does it contain one or more files to be zipped?
  210.                 string[] files = Directory.GetFiles(@".\start", "*.*", SearchOption.TopDirectoryOnly);
  211.                 if(files.Length < 1){
  212.                     Console.WriteLine("\n Subdirectory .\\start doesn't have any files to be zipped.");
  213.                     Console.WriteLine(" Program will terminate.\n");
  214.                 }else{
  215.                    
  216.                     success = true;
  217.                 }
  218.             }            
  219.             return success;
  220.         }
  221.        
  222.         public static void ShowTitle(){
  223.             Console.Clear();
  224.             Console.ForegroundColor = ConsoleColor.Yellow;
  225.             Console.WriteLine("\n running 'simple.exe'...");
  226.             Console.ForegroundColor = ConsoleColor.Gray;
  227.             Console.WriteLine(" kyrathasoft@gmail.com, 6/02/2019");
  228.             Console.ForegroundColor = ConsoleColor.White;
  229.         }
  230.          
  231.     }
  232. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement