C# Fortschritt anzeige

Gotenks666

Ensign
Registriert
Mai 2009
Beiträge
165
Guten Tag liebe Community.

Ich habe ein Programm entwickelt, das mir erlaubt per Knopfdruck eine Datei von der eingebenen URL auf den Pc zu Downloaden.
Der ganze Fortschritt wird in einer Progressbar angezeigt.

Nun möchte ich aber, dass das ganze noch in einer "%" Anzeige dargestellt wird,
und mit wiviel kb/s man diese Datei gerade runterlädt.

Bei der "%" Anzeige habe ich dieses Kommentar gefunden:
Größe der Datei / 100, damit bekommst du 1%schritte

und immer wenn du 1% runtergeladen hast, machst du
progressBar1.increment(GrößederDatei/100);

Ich wäre euch sehr dankbar wen ihr mir helfen könntet.

Hier ist schonmal mein Code, das ihr auch zurechtfindet und mir eventuell helfen könnt.

Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;


namespace Datei Downloader
{
    public partial class Form3 : Form
    {
        public Form3()
        {
            InitializeComponent();
        }


        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            // the URL to download the file from
            string sUrlToReadFileFrom = textBoxSourceFile.Text;
            // the path to write the file to
            int iLastIndex = sUrlToReadFileFrom.LastIndexOf('/');
            string sDownloadFileName = sUrlToReadFileFrom.Substring(iLastIndex + 1, (sUrlToReadFileFrom.Length - iLastIndex - 1));
            string sFilePathToWriteFileTo = textBoxDestinationFolder.Text + "\\" + sDownloadFileName;

            // first, we need to get the exact size (in bytes) of the file we are downloading
            Uri url = new Uri(sUrlToReadFileFrom);
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
            response.Close();
            // gets the size of the file in bytes
            Int64 iSize = response.ContentLength;

            // keeps track of the total bytes downloaded so we can update the progress bar
            Int64 iRunningByteTotal = 0;

            // use the webclient object to download the file
            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                // open the file at the remote URL for reading
                using (System.IO.Stream streamRemote = client.OpenRead(new Uri(sUrlToReadFileFrom)))
                {
                    // using the FileStream object, we can write the downloaded bytes to the file system
                    using (Stream streamLocal = new FileStream(sFilePathToWriteFileTo, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        // loop the stream and get the file into the byte buffer
                        int iByteSize = 0;
                        byte[] byteBuffer = new byte[iSize];
                        while ((iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
                        {
                            // write the bytes to the file system at the file path specified
                            streamLocal.Write(byteBuffer, 0, iByteSize);
                            iRunningByteTotal += iByteSize;

                            // calculate the progress out of a base "100"
                            double dIndex = (double)(iRunningByteTotal);
                            double dTotal = (double)byteBuffer.Length;
                            double dProgressPercentage = (dIndex / dTotal);
                            int iProgressPercentage = (int)(dProgressPercentage * 100);

                            // update the progress bar
                            backgroundWorker1.ReportProgress(iProgressPercentage);
                        }

                        // clean up the file stream
                        streamLocal.Close();
                    }

                    // close the connection to the remote server
                    streamRemote.Close();
                }
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("File download complete");
        }


        private void button1_Click(object sender, EventArgs e)
        {
           
            if (textBoxSourceFile.Text.Length == 0)
            {
                MessageBox.Show("Please enter a source file");
                return;
            }

            if (textBoxDestinationFolder.Text.Length == 0)
            {
                MessageBox.Show("Please enter a destination file");
            }

            backgroundWorker1.RunWorkerAsync();
        }
 
wollte das grade mal erstellen
aber du hast die form im designer erstellt?

ich werd das mal abonieren und mir morgen mal anschauen
kannst du es als zip anhängen?

wir schreiben um 8 abschlussprüfung in C# und ich sollte jetzt echt mal schlafen gehen
 
Das sieht doch theoretisch schon gut aus.
Ich habs jetzt nicht probiert, müsste aber so klappen, wenn das response.getContentlength den richtigen Wert liefert.
 
Vielen Dank für die schnellen Antworten.

Ich möchte die "%" Anzeige in einem Textlabel darstellen.
Doch fehlen mir die Nötigen Kenntnisse um das zu machen.
 
Habe ich nun gemacht, nun habe ich den folgenden Code für die Prozentanzeige:
Code:
  int i = 0;
            int prozent = 0;
            while (i < 100)
            {
                prozent++;
                label1.Text = prozent + "%";
                if (prozent >= progressBar1.Value + 1)
                {
                    label1.Refresh();
                    progressBar1.PerformStep();
                }
                i++;
                Thread.Sleep(50);
            }

Den habe ich nun so eingebaut:

Code:
 private void button1_Click(object sender, EventArgs e)
        {
           
            if (textBoxSourceFile.Text.Length == 0)
            {
                MessageBox.Show("Please enter a source file");
                return;
            }

            if (textBoxDestinationFolder.Text.Length == 0)
            {
                MessageBox.Show("Please enter a destination file");
            }

            backgroundWorker1.RunWorkerAsync();
 [B] int i = 0;
            int prozent = 0;
            while (i < 100)
            {
                prozent++;
                label1.Text = prozent + "%";
                if (prozent >= progressBar1.Value + 1)
                {
                    label1.Refresh();
                    progressBar1.PerformStep();
                }
                i++;
                Thread.Sleep(50);
            }
          [/B]
        }

Nun habe ich aber das Problem,
wen ich den Button drücke fängt er an bis 100 zu zählen und dan fängt er erst an den Download zu starten und die Anzeige bleibt auf 100% stehen.
 
Du musst deinen Fortschrittsbalken auch mit dem Download verknüpfen.


Code:
  while ((iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
                        {
                            // write the bytes to the file system at the file path specified
                            streamLocal.Write(byteBuffer, 0, iByteSize);
                            iRunningByteTotal += iByteSize;

                            // calculate the progress out of a base "100"
                            double dIndex = (double)(iRunningByteTotal);
                            double dTotal = (double)byteBuffer.Length;
                            double dProgressPercentage = (dIndex / dTotal);
                            int iProgressPercentage = (int)(dProgressPercentage * 100);

                            // update the progress bar
                            backgroundWorker1.ReportProgress(iProgressPercentage);
                            label1.text= iProgressPercentage & "%";
                            label1.refresh();
                        }

Vorrausgesetzt enthält die Prozentangabe.
 
Zuletzt bearbeitet:
kann dir bei sowas empfehlen die visuellen komponenten (progressbar) von while-schleifen abzulösen.
sieht nämlich sonst so aus, als müsste der download darauf warten, bis sich die progressbar neugezeichnet hat - wenn sie das überhaupt in einer while-schleife tut.

schau dir mal hier an, wie die threads synchronisiert auf AccessGlobalResource() zugreifen.

lass also einen thread deinen download machen. dabei setze die globalen variablen dTotal, dIndex. ein anderer thread soll nebenläufig jede sekunde diese variablen auslesen und deine progressbar auktualisieren.
 
Zurück
Oben