Partage
  • Partager sur Facebook
  • Partager sur Twitter

C# Comment télécharger un fichier?

Rien ne se passe :(

Sujet résolu
    2 octobre 2011 à 17:43:42

    Re bonjour,

    J'ai pas mal avancer dans mon projet de 'Launcher' Mais j'ai encore une fois un problème. Mais cette fois-ci, au moment du téléchargement du jeu (jeu flash en jar)

    Donc mon launcher, en cliquant sur 'Jouer', vérifie si 'dexongame.jar' existe dans 'AppData\Roaming\dexongame' si le .jar n'existe pas, il ouvre 'Form2' (La page d'installation du .jar) Et mon problème est lorsqu'on clique sur le bouton 'Lancer le téléchargement' Ma bars de progression reste à 0% (sa s'affiche sur la bar) et le fichier ne s'installe pas.

    Voici mon code :
    private void button1_Click(object sender, EventArgs e)
            {
                string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                string filePath = Path.Combine(appDataPath, "dexongame");
    
            //DOWNLOAD
        WebClient client = new WebClient();
        client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
        client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
        
        // Starts the download
        client.DownloadFileAsync(new Uri("http://monsite.com/maj/dexongame.jar"), filePath);
    
        button1.Text = "Téléchargement en cours";
        button1.Enabled = false;
    
    
    
                //PROGRESSBAR
                void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        double bytesIn = double.Parse(e.BytesReceived.ToString());
        double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
        double percentage = bytesIn / totalBytes * 100;
    
        progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());
    }
            void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
    {
        MessageBox.Show("Le téléchargement s'est bien déroulé. Vous pouvez fermer la page et cliquer sur \"Jouer\"");
    
        button1.Text = "Téléchargement fini";
        button1.Enabled = false;
    }
            }
    


    Donc j'ai mis http://monsite.com/maj/dexongame.jar pour masquer mon lien ^.^ mon jeu est pas fini :p

    Aussi, possible de faire en sorte que si je met une nouvelle version du jeu dans http://monsite.com/maj/ sa le détecte et installe cette nouvel mise à jour ?
    Car je veux pas que mes joueurs soient obligé de re télécharger un nouveau launcher à chaque fois :(
    • Partager sur Facebook
    • Partager sur Twitter
    Anonyme
      2 octobre 2011 à 17:51:04

      Salut,

      client.DownloadFileAsync(new Uri("http://monsite.com/maj/dexongame.jar"), filePath);
      


      DownloadFileAsync demande une Uri distante (ce que tu as bien) et un fichier local.
      Or, filePath renvoi vers un dossier, pas vers un fichier !

      (Ou alors vers un fichier sans extension, mais ce n'est tout de même pas ce que tu cherches)

      Remplace :

      string filePath = Path.Combine(appDataPath, "dexongame");
      


      par :

      string directoryPath = Path.Combine(appDataPath, "dexongame");
      if (!Directory.Exists(directoryPath))
          Directory.CreateDirectory(directoryPath);
      string filePath = Path.Combine(directoryPath, "dexongame.jar");
      


      J'en ai profité pour vérifier si le dossier dans appdata existait. Si non, il le crée pour éviter une erreur ;)
      • Partager sur Facebook
      • Partager sur Twitter
        2 octobre 2011 à 18:31:14

        Salut et merci. Mais j'ai quelque petite erreurs que je viens tout juste de voir... d'après moi elles sont là depuis un bout de temps.
        Et je pense que Visual C# Express exécute(F5) le programme sous la dernière form sans aucun bug donc se que je modifie, ne s'exécute pas :euh:

        voici les 2 erreurs :
        Image utilisateur

        et

        Image utilisateur
        Cette dernière erreur, c'est la '}' de la fin. (namespace DexonGame_Launcher { })
        le namespace qui englobe quasiment tout sauf les 'using' exemple: using System.Net; (celui que j'ai rajouter car sur le tuto du mec le disait)

        Mon code en son entier est :
        namespace DexonGame_Launcher
        {
            public partial class Form2 : Form
            {
                public Form2()
                {
                    InitializeComponent();
                }
        
                private void button1_Click(object sender, EventArgs e)
                {
                    string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                    string directoryPath = Path.Combine(appDataPath, "dexongame");
                        if (!Directory.Exists(directoryPath)){Directory.CreateDirectory(directoryPath);}
                    string filePath = Path.Combine(directoryPath, "DexonGame.jar");
        
                //DOWNLOAD
            WebClient client = new WebClient();
            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
            client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
            
            // Starts the download
            client.DownloadFileAsync(new Uri("http://monsite/maj/dexongame.jar"), directoryPath); //directoryPath ou filePath ?
        
            button1.Text = "Téléchargement en cours";
            button1.Enabled = false; 
        
        
        
                    //PROGRESSBAR
                    void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
                    {
                         double bytesIn = double.Parse(e.BytesReceived.ToString());
                         double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
                         double percentage = bytesIn / totalBytes * 100;
        
                         progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());
                    }
                    void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
                    {
                          MessageBox.Show("Le téléchargement s'est bien déroulé. Vous pouvez fermer la page et cliquer sur \"Jouer\"");
        
                            button1.Text = "Téléchargement fini";
                            button1.Enabled = false;
                    }
                }
            }
        }
        
        • Partager sur Facebook
        • Partager sur Twitter
        Anonyme
          2 octobre 2011 à 18:35:05

          Effectivement, on dirait que tu as mis les fonctions client_DownloadProgressChanged et client_DownloadFileCompleted à l'intérieur de la fonction button1_Click !

          C'est absolument impossible en C# et il faut séparer les trois ;)

          Au passage, indente ton code correctement.
          La ligne :

          WebClient client = new WebClient();
          


          Doit être au même niveau que la précédente :

          string filePath = Path.Combine(directoryPath, "DexonGame.jar");
          
          • Partager sur Facebook
          • Partager sur Twitter
            2 octobre 2011 à 18:43:12

            Comment séparer les 3 fonctions?
            et par 'indente' tu veux dire quoi? Je le mets sure la même ligne?
            • Partager sur Facebook
            • Partager sur Twitter
            Anonyme
              2 octobre 2011 à 18:55:37

              Pour séparer les trois fonctions, tu déplaces :

              //PROGRESSBAR
                          void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
                          {
                               double bytesIn = double.Parse(e.BytesReceived.ToString());
                               double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
                               double percentage = bytesIn / totalBytes * 100;
              
                               progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());
                          }
                          void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
                          {
                                MessageBox.Show("Le téléchargement s'est bien déroulé. Vous pouvez fermer la page et cliquer sur \"Jouer\"");
              
                                  button1.Text = "Téléchargement fini";
                                  button1.Enabled = false;
                          }
              


              Après la fermeture du } de :

              private void button1_Click(object sender, EventArgs e)
              {
              // [...]
              // Le code est actuellement ici
              }
              
              // Il faut le mettre ici
              


              Par indentation j'entends que lorsque tu ouvres un bloc (avec une accolade), alors il faut déplacer tout le code de ce bloc de quelques espaces :

              Image utilisateur

              Avec mon image, on voit bien qu'une partie du code est mal indentée, et que les fonctions client_DownloadProgressChanged et client_DownloadFileCompleted sont à l'intérieur du bloc de la fonction button1_Click.
              • Partager sur Facebook
              • Partager sur Twitter
                2 octobre 2011 à 19:08:35

                Merci ! Je ne savais pas que mal indenté pouvais faire de quoi :o sa marche ! :)
                Juste changer 'client.DownloadFileAsync(new Uri("http://monsite/maj/dexongame.jar"), directoryPath);' remplacer directoryPath par filePath, et boom sa fonctionne ! :D
                • Partager sur Facebook
                • Partager sur Twitter
                Anonyme
                  2 octobre 2011 à 19:15:06

                  Je pense surtout qu'il y a eu une erreur lors du téléchargement ;)

                  Regarde du côté de e.Error dans la fonction void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e).

                  Edit : Ah j'ai pas vu que tu as édité. Content que ça fonctionne :D
                  • Partager sur Facebook
                  • Partager sur Twitter

                  C# Comment télécharger un fichier?

                  × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
                  × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
                  • Editeur
                  • Markdown