Récupération d'une fichier sur internet et ProgressBar dans cmd

Résolu/Fermé
Paullux_1er Messages postés 122 Date d'inscription vendredi 10 février 2017 Statut Membre Dernière intervention 28 janvier 2020 - 14 juin 2017 à 21:51
Whismeril Messages postés 19027 Date d'inscription mardi 11 mars 2003 Statut Contributeur Dernière intervention 24 avril 2024 - 16 juin 2017 à 22:11
Bonjour,

J'ai écrit un morceau de code en C#, une Console Application, avec Visual Studio 2015, pour télécharger un fichier zip sur internet et le décompresser pour avoir un fichier XML (fichier contenant les guides des programmes TV des différentes chaines de télévision en France), je l'utilise avec Kodi.

Voici mon Code :
using System;
using System.IO;
using System.IO.Compression;
using System.Net;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Lancement de la mise à jour de l'EPG");
            string pathUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            string extractPath = Path.Combine(pathUser, "Downloads", "EPG Kodi");
            string zipPath = Path.Combine(extractPath, "complet.zip");
            string xmlPath = Path.Combine(extractPath, "complet.xml");
            Console.WriteLine("Effacement des fichiers précédents");
            File.Delete(zipPath);
            File.Delete(xmlPath);
            Console.WriteLine("Téléchargement en cours...");
            using (WebClient mywebClient = new WebClient())
            {
                mywebClient.DownloadFile("http://xmltv.dtdns.net/download/complet.zip", zipPath);
                Console.WriteLine("#");
             }
            Console.WriteLine("Téléchargement terminé");
            Console.WriteLine("Extraction du fichier");
            ZipFile.ExtractToDirectory(zipPath, extractPath);
            Console.WriteLine("Finit");
        }
    }
}


Ma question est comment avoir de manière simple une barre de défilement dans l'invite de commande ouverte par le programme ?

comme par exemple ici https://stackoverflow.com/questions/24918768/progress-bar-in-console-application celle avec des dièses verts...


A voir également:

8 réponses

Whismeril Messages postés 19027 Date d'inscription mardi 11 mars 2003 Statut Contributeur Dernière intervention 24 avril 2024 931
14 juin 2017 à 21:59
ben en suivant les explications du post ou il y a la progressBar verte...
0
Paullux_1er Messages postés 122 Date d'inscription vendredi 10 février 2017 Statut Membre Dernière intervention 28 janvier 2020 1
14 juin 2017 à 22:14
Suis-je obliger de télécharger des programmes supplémentaires, n'existe-il pas des fonction existant directement dans visual studio simple et efficace ?
Je n'est pas un très grand niveau en C#.
0
Whismeril Messages postés 19027 Date d'inscription mardi 11 mars 2003 Statut Contributeur Dernière intervention 24 avril 2024 931
14 juin 2017 à 23:12
Je n'ai pas essayé, mais vu que la réponse avec 7 votes montre une coche verte, c'est qu'elle a répondu à la question initiale.
Cette réponse ne mets pas en œuvre d'outils spécifiques.

Après le code sert à montrer l'avancée d'un téléchargement de plusieurs fichiers et s'incrémente à chaque nouveau fichier.
Dans ton cas, si tu n'as qu'un seul fichier.

Dans ton cas, il faut savoir si ton outils mywebClient envoie un état régulier du téléchargement.
0
Paullux_1er Messages postés 122 Date d'inscription vendredi 10 février 2017 Statut Membre Dernière intervention 28 janvier 2020 1
Modifié le 15 juin 2017 à 22:17
J'ai amélioré mon code :

using System;
using System.ComponentModel;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static string pathUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
        static string extractPath = Path.Combine(pathUser, "Downloads", "EPG Kodi");
        static string zipPath = Path.Combine(extractPath, "complet.zip");
        static string xmlPath = Path.Combine(extractPath, "complet.xml");
        static string adresse = "http://xmltv.dtdns.net/download/complet.zip";

        static void Main(string[] args)
        {
            Console.WriteLine("Lancement de la mise à jour de l'EPG");
            Console.WriteLine("Effacement des fichiers précédents");
            File.Delete(zipPath);
            File.Delete(xmlPath);
            Console.WriteLine("Lancement du téléchargement en cours...");
            DownLoadFileInBackground2(adresse);
            Thread.Sleep(30000);
        }

        public static void DownLoadFileInBackground2(string address)
        {
            Uri uri = new Uri(address);
            WebClient mywebClient = new WebClient();
            // Specify that the DownloadFileCallback method gets called
            // when the download completes.
            mywebClient.DownloadFileCompleted += new AsyncCompletedEventHandler (HandleDownloadComplete);
            // Specify a progress notification handler.
            mywebClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler (mywebClient_DownloadProgressChanged);
            mywebClient.DownloadFileAsync(uri, zipPath);
        }

        private static void mywebClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            try
            {
                Console.WriteLine("{0}    téléchargement {1} sur {2} octet(s). {3} % téléchargement effectué...",
                (string)e.UserState,
                e.BytesReceived,
                e.TotalBytesToReceive,
                e.ProgressPercentage);
             }
            catch (Exception ex) { Console.WriteLine("Echec du téléchargement : " + ex.Message); }
        }
        private static void HandleDownloadComplete(object sender, AsyncCompletedEventArgs e)
        {
            Console.WriteLine("Téléchargement terminé");
            Console.WriteLine("Extraction du fichier");
            ZipFile.ExtractToDirectory(zipPath, extractPath);
            Console.WriteLine("Finit");
            Thread.Sleep(500);
            Environment.Exit(0);
        }
    }
}
0
Whismeril Messages postés 19027 Date d'inscription mardi 11 mars 2003 Statut Contributeur Dernière intervention 24 avril 2024 931
15 juin 2017 à 21:22
Ok, ça marche, mais tu as trouvé une discussion avec une barre de progression, ou il y a 3 solutions et au final tu ne t'en sers pas.
0
Whismeril Messages postés 19027 Date d'inscription mardi 11 mars 2003 Statut Contributeur Dernière intervention 24 avril 2024 931
15 juin 2017 à 21:25
        private static void mywebClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            try
            {
                drawTextProgressBar(e.ProgressPercentage, 100);
            }
            catch (Exception ex) { Console.WriteLine("Echec du téléchargement : " + ex.Message); }
        }

        private static void drawTextProgressBar(int progress, int total)
        {
            //draw empty progress bar
            Console.CursorLeft = 0;
            Console.Write("["); //start
            Console.CursorLeft = 32;
            Console.Write("]"); //end
            Console.CursorLeft = 1;
            float onechunk = 30.0f / total;

            //draw filled part
            int position = 1;
            for (int i = 0; i < onechunk * progress; i++)
            {
                Console.BackgroundColor = ConsoleColor.Gray;
                Console.CursorLeft = position++;
                Console.Write(" ");
            }

            //draw unfilled part
            for (int i = position; i <= 31; i++)
            {
                Console.BackgroundColor = ConsoleColor.Green;
                Console.CursorLeft = position++;
                Console.Write(" ");
            }

            //draw totals
            Console.CursorLeft = 35;
            Console.BackgroundColor = ConsoleColor.Black;
            Console.Write(progress.ToString() + " of " + total.ToString() + "    "); //blanks at the end remove any excess
        }


J'ai juste copié coller le code de la question et je l'ai appelé.
0
Paullux_1er Messages postés 122 Date d'inscription vendredi 10 février 2017 Statut Membre Dernière intervention 28 janvier 2020 1
16 juin 2017 à 13:09
tu sais pourquoi, il y a des "bugs" d'affichage, déplacement de un ou deux pixels de la barre de téléchargement, superposition aléatoire, apparition du curseur aléatoirement, création d'une nouvelle ligne, etc.
0
Whismeril Messages postés 19027 Date d'inscription mardi 11 mars 2003 Statut Contributeur Dernière intervention 24 avril 2024 931
16 juin 2017 à 13:12
Non, comme je te l'ai dit j'ai juste essayé le code existant
0
Paullux_1er Messages postés 122 Date d'inscription vendredi 10 février 2017 Statut Membre Dernière intervention 28 janvier 2020 1
16 juin 2017 à 14:17
Je pense que le pb doit venir du fait, que le code essaye d'écrire une nouvelle ligne alors que la précédente n'est pas finit, je dois donc ajouté une temporisation de 200ms avant de rappeler le drawTextProgressBar
0

Vous n’avez pas trouvé la réponse que vous recherchez ?

Posez votre question
Paullux_1er Messages postés 122 Date d'inscription vendredi 10 février 2017 Statut Membre Dernière intervention 28 janvier 2020 1
16 juin 2017 à 06:55
hier j'ai du dormir,... pour obtenir la version que j'ai dit l'améliorer, je me suis couché à 4h00...

j'ai eu besoin de récupérer...

je regarderai ton commentaire ce soir
0
Paullux_1er Messages postés 122 Date d'inscription vendredi 10 février 2017 Statut Membre Dernière intervention 28 janvier 2020 1
16 juin 2017 à 20:11
Merci Whismeril...

Ca fonctionne...

using System;
using System.ComponentModel;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Threading;

namespace ConsoleApplication1
{
class Program
{
static string DossierUtilisateur = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
static string DossierEPG = Path.Combine(DossierUtilisateur, "Downloads", "EPG Kodi");
static string FichierZip = Path.Combine(DossierEPG, "complet.zip");
static string FichierXML = Path.Combine(DossierEPG, "complet.xml");
static string adresse = "http://xmltv.dtdns.net/download/complet.zip";
static bool TraceLigne = true;

static void Main(string[] args)
{
Console.WriteLine("Lancement de la mise à jour de l'EPG");
Console.WriteLine("Effacement des fichiers précédents");
File.Delete(FichierZip);
File.Delete(FichierXML);
Console.WriteLine("Lancement du téléchargement en cours...");
TelechagementEnFond(adresse);
Thread.Sleep(60000);
}

public static void TelechagementEnFond(string address)
{
Uri uri = new Uri(address);
WebClient MonClientWeb = new WebClient();
// Specify that the DownloadFileCallback method gets called
// when the download completes.
MonClientWeb.DownloadFileCompleted += new AsyncCompletedEventHandler (TelechagementTermine);
// Specify a avancement notification handler.
MonClientWeb.DownloadProgressChanged += new DownloadProgressChangedEventHandler (TelechagementEnCours);
MonClientWeb.DownloadFileAsync(uri, FichierZip);
}

private static void TelechagementEnCours(object sender, DownloadProgressChangedEventArgs e)
{
try
{
if ( TraceLigne == true )
{
DessinerBarreDeavancementionText(e.ProgressPercentage, 100);
}
}
catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Echec du téléchargement : " + ex.Message); }
}
private static void DessinerBarreDeavancementionText(int avancement, int tot)
{
//draw empty avancement bar
TraceLigne = false;
Console.CursorLeft = 0;
Console.Write("["); //start
Console.CursorLeft = 32;
Console.Write("]"); //end
Console.CursorLeft = 1;
float RepresentationPourcentageSurTrente = 30.0f / tot;

//draw filled part
int position = 1;
for (int i = 0; i < RepresentationPourcentageSurTrente * avancement; i++)
{
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.CursorLeft = position++;
Console.Write("#");
}

//draw unfilled part
for (int i = position; i <= 31; i++)
{
Console.ForegroundColor = ConsoleColor.Gray;
Console.CursorLeft = position++;
Console.Write("-");
}

//draw totals
Console.CursorLeft = 35;
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write(avancement.ToString() + "%" + " téléchargé(s) sur " + tot.ToString() + "%" + " "); //blanks at the end remove any excess
TraceLigne = true;
}

private static void TelechagementTermine(object sender, AsyncCompletedEventArgs e)
{
Thread.Sleep(500);
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine("");
Console.WriteLine("Téléchargement terminé");
Console.WriteLine("Extraction du fichier");
ZipFile.ExtractToDirectory(FichierZip, DossierEPG);
Console.WriteLine("Finit");
Thread.Sleep(500);
Environment.Exit(0);
}
}
}
0
Whismeril Messages postés 19027 Date d'inscription mardi 11 mars 2003 Statut Contributeur Dernière intervention 24 avril 2024 931
16 juin 2017 à 20:28
De rien, je n'ai rien fait!
J'ai juste copié le code que tu avais toi même trouvé!
0
Paullux_1er Messages postés 122 Date d'inscription vendredi 10 février 2017 Statut Membre Dernière intervention 28 janvier 2020 1
16 juin 2017 à 20:29
ok,

Une dernière question comment créer un dossier qui n'existe pas ?
0
Whismeril Messages postés 19027 Date d'inscription mardi 11 mars 2003 Statut Contributeur Dernière intervention 24 avril 2024 931
16 juin 2017 à 22:11
Avec la classe Directory.
0
Paullux_1er Messages postés 122 Date d'inscription vendredi 10 février 2017 Statut Membre Dernière intervention 28 janvier 2020 1
Modifié le 16 juin 2017 à 21:20
VERSION FINALE :

using System;
using System.ComponentModel;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Threading;

namespace ConsoleApplication1
{
class Program
{
static string DossierUtilisateur = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
static string DossierEPG = Path.Combine(DossierUtilisateur, "Documents", "EPG Kodi");
static string FichierZip = Path.Combine(DossierEPG, "complet.zip");
static string FichierXML = Path.Combine(DossierEPG, "complet.xml");
static string adresse = "http://xmltv.dtdns.net/download/complet.zip";
static bool TraceLigne = true;

static void Main(string[] args)
{
Console.WriteLine("Lancement de la mise à jour de l'EPG");
if (!Directory.Exists(DossierEPG))
{
Console.WriteLine("Création du Dossier EPG dans le Dossier 'Documents'");
Directory.CreateDirectory(DossierEPG);
}
if (File.Exists(FichierZip))
{
Console.WriteLine("Effacement du fichier Zip précédent");
File.Delete(FichierZip);
}
if (File.Exists(FichierXML))
{
Console.WriteLine("Effacement du fichier XML précédent");
File.Delete(FichierXML);
}
Console.WriteLine("Lancement du téléchargement du nouveau fichier Zip en cours...");
TelechagementEnFond(adresse);
Thread.Sleep(60000);
}

public static void TelechagementEnFond(string address)
{
Uri uri = new Uri(address);
WebClient MonClientWeb = new WebClient();
// Specify that the DownloadFileCallback method gets called
// when the download completes.
MonClientWeb.DownloadFileCompleted += new AsyncCompletedEventHandler (TelechagementTermine);
// Specify a avancement notification handler.
MonClientWeb.DownloadProgressChanged += new DownloadProgressChangedEventHandler (TelechagementEnCours);
MonClientWeb.DownloadFileAsync(uri, FichierZip);
}

private static void TelechagementEnCours(object sender, DownloadProgressChangedEventArgs e)
{
try
{
if ( TraceLigne == true )
{
DessinerBarreDeavancementionText(e.ProgressPercentage, 100);
}
}
catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Echec du téléchargement : " + ex.Message); }
}
private static void DessinerBarreDeavancementionText(int avancement, int tot)
{
//draw empty avancement bar
TraceLigne = false;
Console.CursorLeft = 0;
Console.Write("["); //start
Console.CursorLeft = 32;
Console.Write("]"); //end
Console.CursorLeft = 1;
float RepresentationPourcentageSurTrente = 30.0f / tot;

//draw filled part
int position = 1;
for (int i = 0; i < RepresentationPourcentageSurTrente * avancement; i++)
{
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.CursorLeft = position++;
Console.Write("#");
}

//draw unfilled part
for (int i = position; i <= 31; i++)
{
Console.ForegroundColor = ConsoleColor.Gray;
Console.CursorLeft = position++;
Console.Write("-");
}

//draw totals
Console.CursorLeft = 35;
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write(avancement.ToString() + "%" + " téléchargé(s) sur " + tot.ToString() + "%" + " "); //blanks at the end remove any excess
TraceLigne = true;
}

private static void TelechagementTermine(object sender, AsyncCompletedEventArgs e)
{
Thread.Sleep(500);
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine("");
Console.WriteLine("Téléchargement terminé");
Console.WriteLine("Extraction du fichier Zip en cours...");
ZipFile.ExtractToDirectory(FichierZip, DossierEPG);
Console.WriteLine("Finit");
Thread.Sleep(500);
Environment.Exit(0);
}
}
}


Lien de Téléchargement du binaire compilé :
https://drive.google.com/drive/folders/0B7PjzAwMEwKsZmVzM1I1LXZjaDA?usp=sharing
0