Forum |  HardWare.fr | News | Articles | PC | S'identifier | S'inscrire | Shop Recherche
2422 connectés 

  FORUM HardWare.fr
  Programmation
  C#/.NET managed

  Dézippé un fichier

 


 Mot :   Pseudo :  
 
Bas de page
Auteur Sujet :

Dézippé un fichier

n°2272948
xnooztv
Posté le 07-01-2016 à 16:39:28  profilanswer
 

Bonjour,  
 
Voila, je suis sur la création d'un launcher et je souhaite dézippé le fichier dans le dossier ou se trouve le launcher.  
Mon launcher récupère un fichier de configuration sur mon site, voici le fichier conf.txt:  
 

http://lsl-rp.ga/landwars/update/version.txt http://lsl-rp.ga/landwars/update/maj.zip DOSSIER_LORS_DU_DEZIP


 
Donc, quand mon launcher dézip le fichier maj.zip, il crée un dossier "DOSSIER_LORS_DU_DEZIP" et les fichiers sont dedans.  
Mais, je souhaiterais dézippé maj.zip dans le dossier ou se trouve mon launcher.  
 
Voici mon code:
 

Code :
  1. using ICSharpCode.SharpZipLib.Zip;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Diagnostics;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. using System.Windows;
  12. using System.Windows.Controls;
  13. using System.Windows.Data;
  14. using System.Windows.Documents;
  15. using System.Windows.Input;
  16. using System.Windows.Media;
  17. using System.Windows.Media.Imaging;
  18. using System.Windows.Navigation;
  19. using System.Windows.Shapes;
  20. namespace Launcher
  21. {
  22.     /// <summary>
  23.     /// Logique d'interaction pour MainWindow.xaml
  24.     /// </summary>
  25.     enum UpdateState { search, available, download, update };
  26.     public partial class MainWindow : Window
  27.     {
  28.         private string m_confUrl = "http://lsl-rp.ga/landwars/update/conf.txt";
  29.         //Variable de configuration
  30.         string m_versionUrl = null, m_zipUrl = null, m_unziPath = null;
  31.         private UpdateState m_updateState;
  32.         public MainWindow()
  33.         {
  34.             InitializeComponent();
  35.             m_updateState = UpdateState.search;
  36.             //Si l'évenement this.Close() est appeler.
  37.             this.Closing += delegate
  38.             {
  39.                 if (m_updateState == UpdateState.download) //Si le téléchargement est en cours.
  40.                 {
  41.                     if (MessageBox.Show("Le téléchargement sera annuler si vous quittez.", "Voulez vous quitter ?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
  42.                     {
  43.                         this.Close();
  44.                     }
  45.                 }
  46.             };
  47.             //Téléchargement du fichier de configuration
  48.             WebClient request = new WebClient();
  49.             request.DownloadFile(m_confUrl, "Landwars_Data/conf.txt" );
  50.             //Lecture du fichier
  51.             StreamReader initReader;
  52.             initReader = new StreamReader("Landwars_Data/conf.txt" );
  53.             string lineRead = initReader.ReadLine();
  54.             if (lineRead != null)
  55.             {
  56.                 string[] settingLine = lineRead.Split(' ');
  57.                 m_versionUrl = settingLine[0];
  58.                 m_zipUrl = settingLine[1];
  59.                 m_unziPath = settingLine[2];
  60.             }
  61.             else
  62.                 MessageBox.Show("Erreur: Fichier de configuration illisible", "ERREUR", MessageBoxButton.OK, MessageBoxImage.Stop);
  63.             initReader.Close();
  64.             //Vérification de la version, mise à jour ou non.
  65.             if (File.Exists("Landwars_Data/version.txt" )) // Voir si le fichier version.txt existe sur l'ordinateur.
  66.             {
  67.                 Stream data = request.OpenRead(m_versionUrl); // Lire la version en ligne du version
  68.                 StreamReader reader = new StreamReader(data);
  69.                 string onlineVersion = reader.ReadLine();
  70.                 reader.Close();
  71.                 StreamReader localVersionStream;//Local
  72.                 localVersionStream = new StreamReader("Landwars_Data/version.txt" );
  73.                 string localVersion = localVersionStream.ReadLine();
  74.                 localVersionStream.Close();
  75.                 if (onlineVersion == localVersion) //Si il existe, vérifier que le client est à jour
  76.                 {
  77.                     //Tout est à jour
  78.                     m_updateState = UpdateState.update;
  79.                 }
  80.                 else
  81.                 {
  82.                     //Mise à jour
  83.                     m_updateState = UpdateState.available;
  84.                     Download();
  85.                 }
  86.             }
  87.             else //Si il n'existe pas, alors mise à jour.
  88.             {
  89.                 //Mise à jour
  90.                 m_updateState = UpdateState.available;
  91.                 Download();
  92.             }
  93.         }
  94.         //Update
  95.         private bool Download()
  96.         {
  97.             if (m_updateState == UpdateState.available)
  98.             {
  99.                 m_updateState = UpdateState.download;
  100.                 Play.Content = "Mise à jour en cours ..."; //On change le texte
  101.                 Play.Margin = new Thickness(304, 104, 0, 0);
  102.                 WebClient webClient = new WebClient();
  103.                 webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
  104.                 webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
  105.                 webClient.DownloadFileAsync(new Uri(m_zipUrl), "maj.zip" );
  106.             }
  107.             return true;
  108.         }
  109.         private void Completed(object sender, AsyncCompletedEventArgs e)
  110.         {
  111.             Play.Margin = new Thickness(602, 104, 0, 0);
  112.             Play.Content = "Jouer";
  113.             if (Directory.Exists(m_unziPath)) //On supprime l'ancienne version.
  114.             {
  115.                 string[] filePaths = Directory.GetFiles(m_unziPath);
  116.                 foreach (string filePath in filePaths)
  117.                     File.Delete(filePath);
  118.             }
  119.             Decompress("maj.zip", m_unziPath, true);
  120.             //Mettre à jour le version.txt local
  121.             WebClient webClient = new WebClient();
  122.             webClient.DownloadFile(new Uri(m_versionUrl), "Landwars_Data/version.txt" );
  123.             m_updateState = UpdateState.update;
  124.         }
  125.         private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
  126.         {
  127.             Play.Content = "Mise à jour en cours (" + e.ProgressPercentage + "%)";
  128.         }
  129.         //Button Event
  130.         private void OfficialWebSite_Click(object sender, RoutedEventArgs e)
  131.         {
  132.             Process.Start("https://minecraft.net/" );
  133.         }
  134.         private void Exit_Click(object sender, RoutedEventArgs e)
  135.         {
  136.             this.Close();
  137.         }
  138.         private void Play_Click(object sender, RoutedEventArgs e)
  139.         {
  140.             if(m_updateState == UpdateState.update)
  141.             {
  142.                 //Lancement de votre exécutable
  143.                 System.Diagnostics.ProcessStartInfo start = new System.Diagnostics.ProcessStartInfo();
  144.                 start.FileName = ".exe";
  145.                 start.WorkingDirectory = m_unziPath;
  146.                 System.Diagnostics.Process.Start(start);
  147.             }
  148.         }
  149.         //Unzip
  150.         public bool Decompress(string source, string destinationDirectory, bool deleteOriginal = false)
  151.         {
  152.             //Ouverture d'un nouveau contexte ZipInputStream (Librairie)
  153.             using (var zipStream = new ZipInputStream(File.OpenRead(source)))
  154.             {
  155.                 ZipEntry entry = null;
  156.                 string tempEntry = string.Empty;
  157.                 while ((entry = zipStream.GetNextEntry()) != null)
  158.                 {
  159.                     string fileName = System.IO.Path.GetFileName(entry.Name);
  160.                     if (destinationDirectory != string.Empty)
  161.                         Directory.CreateDirectory(destinationDirectory);
  162.                     if (!string.IsNullOrEmpty(fileName))
  163.                     {
  164.                         if (entry.Name.IndexOf(".ini" ) < 0)
  165.                         {
  166.                             string path = destinationDirectory + @"\" + entry.Name;
  167.                             path = path.Replace("\\ ", "\\" );
  168.                             string dirPath = System.IO.Path.GetDirectoryName(path);
  169.                             if (!Directory.Exists(dirPath))
  170.                                 Directory.CreateDirectory(dirPath);
  171.                             using (var stream = File.Create(path))
  172.                             {
  173.                                 int size = 2048;
  174.                                 byte[] data = new byte[2048];
  175.                                 byte[] buffer = new byte[size];
  176.                                 while (true)
  177.                                 {
  178.                                     size = zipStream.Read(buffer, 0, buffer.Length);
  179.                                     if (size > 0)
  180.                                         stream.Write(buffer, 0, size);
  181.                                     else
  182.                                         break;
  183.                                 }
  184.                             }
  185.                         }
  186.                     }
  187.                 }
  188.             }
  189.             if (deleteOriginal)
  190.                 File.Delete(source);
  191.             return true;
  192.         }
  193.     }
  194. }


 
Pour informations, j'ai déjà essayer de retirer "DOSSIER_LORS_DU_DEZIP" ou de le remplacer par un "/" ou un "\", mon launcher crash (ce que je comprend)
 
Je ne veux pas utiliser ClickOne.
 
Car enfaîte, je développe un jeu et mon launcher fera les mises à jours, et si j'utilise ClickOne, ce sera juste le launcher qui se mettra à jour (d'après ce que je sais, dites moi si je me trompe).
 
Si quelqu'un aurais une idée..  
 
 
Cordialement.

mood
Publicité
Posté le 07-01-2016 à 16:39:28  profilanswer
 

n°2272950
TotalRecal​l
Posté le 07-01-2016 à 16:47:49  profilanswer
 

Je ne comprend pas ta difficulté, si tu développes des jeux et si tu as pu écrire le code ci-dessus, quel est ton souci pour modifier  
 
m_unziPath = settingLine[2];
 
Et  
           string path = destinationDirectory + @"\" + entry.Name;
                            path = path.Replace("\\ ", "\\" );
                            string dirPath = System.IO.Path.GetDirectoryName(path);
                            if (!Directory.Exists(dirPath))
                                Directory.CreateDirectory(dirPath);
 
Pour gérer ton chemin de sortie comme tu le souhaites ?


---------------
Réalisation amplis classe D / T      Topic .Net - C# @ Prog
n°2272954
xnooztv
Posté le 07-01-2016 à 17:06:35  profilanswer
 

C'est un petit jeu et j'ai lu un tutoriel pour le launcher sur internet mais il n'explique pas la fonction ZIP (je souhaite m’entraîner au C#, à comprendre le code)
 
Que doit-je faire exactement sur les deux bouts de codes que tu m'a donner?


Message édité par xnooztv le 07-01-2016 à 17:07:22
n°2272958
TotalRecal​l
Posté le 07-01-2016 à 18:31:36  profilanswer
 

C'est juste du bidouillage de chaîne, avec le débuggeur tu dois rapidement comprendre comment il bricole son chemin...
 
A mon avis t'as juste à remplacer  
m_unziPath = settingLine[2];  
par  
m_unziPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
 
Et voir si ça renvoie bien ce que tu attends avec ton ami le débuggeur.
 
Tu pourras virer ton dernier paramètre qui ne servira plus.


---------------
Réalisation amplis classe D / T      Topic .Net - C# @ Prog
n°2272969
xnooztv
Posté le 07-01-2016 à 21:13:07  profilanswer
 

Sa ne fonctionne pas.. :/

n°2272971
xnooztv
Posté le 07-01-2016 à 21:22:24  profilanswer
 

J'ai regarder vite fais la documentation et maintenant sa fonctionne!
 
Pour ceux qui sa intéresse:
 

Code :
  1. public void ExtractZipFile(string archiveFilenameIn, string password, string outFolder)
  2.         {
  3.             ZipFile zf = null;
  4.             try
  5.             {
  6.                 FileStream fs = File.OpenRead(archiveFilenameIn);
  7.                 zf = new ZipFile(fs);
  8.                 if (!String.IsNullOrEmpty(password))
  9.                 {
  10.                     zf.Password = password;     // AES encrypted entries are handled automatically
  11.                 }
  12.                 foreach (ZipEntry zipEntry in zf)
  13.                 {
  14.                     if (!zipEntry.IsFile)
  15.                     {
  16.                         continue;           // Ignore directories
  17.                     }
  18.                     String entryFileName = zipEntry.Name;
  19.                     // to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName);
  20.                     // Optionally match entrynames against a selection list here to skip as desired.
  21.                     // The unpacked length is available in the zipEntry.Size property.
  22.                     byte[] buffer = new byte[4096];     // 4K is optimum
  23.                     Stream zipStream = zf.GetInputStream(zipEntry);
  24.                     // Manipulate the output filename here as desired.
  25.                     String fullZipToPath = System.IO.Path.Combine(outFolder, entryFileName);
  26.                     string directoryName = System.IO.Path.GetDirectoryName(fullZipToPath);
  27.                     if (directoryName.Length > 0)
  28.                         Directory.CreateDirectory(directoryName);
  29.                     // Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size
  30.                     // of the file, but does not waste memory.
  31.                     // The "using" will close the stream even if an exception occurs.
  32.                     using (FileStream streamWriter = File.Create(fullZipToPath))
  33.                     {
  34.                         StreamUtils.Copy(zipStream, streamWriter, buffer);
  35.                     }
  36.                 }
  37.             }


 
 
Le code pour extraire un fichier:
 

Code :
  1. ExtractZipFile("fichier.zip", "MotDePasseSinonMettezRien", "DossierDeDestination" );


Message édité par xnooztv le 07-01-2016 à 21:26:48

Aller à :
Ajouter une réponse
  FORUM HardWare.fr
  Programmation
  C#/.NET managed

  Dézippé un fichier

 

Sujets relatifs
BATCH, FOR/R rename fichier avec espace dans le nom[HTA / JAVA] Comment ouvrir un fichier
Un fichier à décoderFichier batch
Ecrire totalité des resultats d'un programme dans un fichier en CManière optimale de lire un fichier
Manière optimale de lire un fichierSecuriser le transfert de fichier
Excel : Code macro pour aller chercher les données d'un autre fichierProblème d'impression de fichier html contenant un saut de page
Plus de sujets relatifs à : Dézippé un fichier


Copyright © 1997-2022 Hardware.fr SARL (Signaler un contenu illicite / Données personnelles) / Groupe LDLC / Shop HFR