7 Replies - 846 Views - Last Post: 31 January 2012 - 09:37 AM Rate Topic: -----

#1 vbob  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 31-January 12

Transform Bytes in MB if...else and speed meter

Posted 31 January 2012 - 07:25 AM

Well, I was followin a tutorial "how to create a Download Manager in C#"...

So, I created it without problems.

Now, I want to add a Speed Meter, and I want that the labels use MB just if the TotalBytes are in MB....

PS: My // tags are in portuguese, beacuse I'm brazilian, sorry....

See the code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Threading;
using System.Diagnostics;

namespace DownloadManager
{    
    public partial class Form1 : Form
    {
        // A thread no qual o download acontece
        private Thread thrDownload;
        // O fluxo de dados pegos do servidor do arquivo
        private Stream strResponse;
        // O fluxo de dados para serem escritos no HD
        private Stream strLocal;
        // O pedido de informacoes sobre o arquivo a ser baixado
        private HttpWebRequest webRequest;
        // A resposta do servidor sobre as informacoes do arquivo
        private HttpWebResponse webResponse;
        // O progresso do download em porcentagem
        private static int PercentProgress;
        // O delegate a ser chamado da thread para atualizar o formulário
        private delegate void UpdateProgessCallback(Int64 BytesRead, Int64 TotalBytes);
       
        
        public Form1()
        {
            InitializeComponent();
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            // Deixar o user saber que estamos nos conectando ao servidor
            lblProgress.Text = "Download Starting";
            // Criar uma nova thread que chama o método Download()
            thrDownload = new Thread(Download);
            // Comecar a thread e chamar o metodo Download()
            thrDownload.Start();
            
        }

        private void UpdateProgress(Int64 BytesRead, Int64 TotalBytes)
        {
            
            // Calcular o progresso do download em porcentagem
            PercentProgress = Convert.ToInt32((BytesRead * 100) / TotalBytes);
            // Mak progress on the progress bar
            prgDownload.Value = PercentProgress;

            if (TotalBytes <= 1000000)  
            {
            TotalBytes = Convert.ToInt32(TotalBytes / 1024f);
            }
                    
            else 
            { 
            TotalBytes = Convert.ToInt32((TotalBytes / 1024f) / 1024f);
            }

            if (BytesRead <= 1000000)
            {
            BytesRead = Convert.ToInt32(BytesRead / 1024f);
            }

            else
            {
            BytesRead = Convert.ToInt32((BytesRead / 1024f) / 1024f);
            }
            
            // Mostrar o progresso atual no label
            lblProgress.Text = "Downloaded " + BytesRead  + "MB out of " + TotalBytes + " MB (" + PercentProgress + "%)";
                   }
        private void Download()
        {
            using (WebClient wcDownload = new WebClient())
            {
                try
                {
                    // Criar um request do arquivo que vamos baixar
                    webRequest = (HttpWebRequest)WebRequest.Create(txtUrl.Text);
                    // Setar a autenticação para download do arquivo
                    webRequest.Credentials = CredentialCache.DefaultCredentials;
                    // Captar a resposta do servidor
                    webResponse = (HttpWebResponse)webRequest.GetResponse();
                    // Pedir para o servidor o tamanho do arquivo e o armazenar
                    Int64 fileSize = webResponse.ContentLength;

                    // Abrir a URL de download
                    strResponse = wcDownload.OpenRead(txtUrl.Text);
                    // Criar um tráfego de dados à serem salvos no HD
                    strLocal = new FileStream(txtPath.Text, FileMode.Create, FileAccess.Write, FileShare.None);

                    // Vai gravar o tamanho do arquivo
                    int bytesSize = 0;
                    // Buffer para armazenar os dados do servidor
                    byte[] downBuffer = new byte[2048];

                    // Loop pelo buffer até estar vazio
                    while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0)
                    {
                        // Escrever os dados do Buffer no HD
                        strLocal.Write(downBuffer, 0, bytesSize);
                        // Invocar o método que atualiza a PrgBar e o Label
                        this.Invoke(new UpdateProgessCallback(this.UpdateProgress), new object[] { strLocal.Length, fileSize });

                    }
                }
                finally               
                {
                    // Quando o código acima estivar concluído, fechar as strings e altrar a label
                    strResponse.Close();
                    strLocal.Close();

                }
                {
                   
                }
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            // Fechar a resposta do servidor e strings
            webResponse.Close();

            strResponse.Close();
            strLocal.Close();
            // Abortar a Thread de Download
            thrDownload.Abort();
            // Setar a PrgBar de volta à 0 e o Label
            prgDownload.Value = 0;
                        lblProgress.Text = "Download Stopped";
        }

        private void txtUrl_TextChanged(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }
    }
}



Is This A Good Question/Topic? 0
  • +

Replies To: Transform Bytes in MB if...else and speed meter

#2 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5632
  • View blog
  • Posts: 12,078
  • Joined: 02-June 10

Re: Transform Bytes in MB if...else and speed meter

Posted 31 January 2012 - 07:53 AM

You've told us what you want.

But you haven't said what the problem is.

How can we help you?
Was This Post Helpful? 1
  • +
  • -

#3 vbob  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 31-January 12

Re: Transform Bytes in MB if...else and speed meter

Posted 31 January 2012 - 08:10 AM

Sorry, the problem is: I want to
 {if (TotalBytes <= 1000)  
            {
            TotalBytes = Convert.ToInt32(TotalBytes / 1024f);
            }
                    
            else 
            { 
            TotalBytes = Convert.ToInt32((TotalBytes / 1024f) / 1024f);
            }

            if (BytesRead <= 1000)
            {
            BytesRead = Convert.ToInt32(BytesRead / 1024f);
            }

            else
            {
            BytesRead = Convert.ToInt32((BytesRead / 1024f) / 1024f);
            }
            
            // Mostrar o progresso atual no label
            lblProgress.Text = "Downloaded " + BytesRead  + "MB out of " + TotalBytes + " MB (" + PercentProgress + "%)";
                   }


But it doesn't work. And I want a help of how can make a speed meter on it
Was This Post Helpful? 0
  • +
  • -

#4 Curtis Rutland  Icon User is offline

  • (╯°□°)╯︵ (~ .o.)~
  • member icon


Reputation: 4559
  • View blog
  • Posts: 7,980
  • Joined: 08-June 10

Re: Transform Bytes in MB if...else and speed meter

Posted 31 January 2012 - 08:38 AM

First, you need to take a look at your logic. What you're doing is saying "if there are less than 1000 bytes, show it as kB. If there are more, show as MB." That doesn't really make sense. Also, it's easier to start at the top and work your way down.

Second, you definitely don't want to overwrite your TotalBytes and BytesRead variables. Those should probably hold your actual integral values. You need a separate value for display purposes. A string would work well, since you can include the unit (MB/kB/bytes) with it.

So, something like this:

const double MB = 1048576;
const double KB = 1024;
string total;

if (TotalBytes >= MB) {
    double t = TotalBytes / MB;
    total = string.Format("{0:0.##} MB", t);
}
else if (TotalBytes >= KB) {
    double t = TotalBytes / KB;
    total = string.Format("{0:0.##} kB", t);
}
else {
    total = string.Format("{0} bytes", TotalBytes);
}



Now, see if you can extract that into a method, so you don't have to write the same thing for BytesRead.
Was This Post Helpful? 2
  • +
  • -

#5 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5632
  • View blog
  • Posts: 12,078
  • Joined: 02-June 10

Re: Transform Bytes in MB if...else and speed meter

Posted 31 January 2012 - 08:38 AM

"It doesn't work" isn't good enough - Read this article first


vbobWhat this shows us is that you aren't familiar with breakpoints and how to debug your own code. Learning to debug one's own code is an essential skill. Sadly, one that apparently no college course teaches. Silly if you ask me.

Placing breakpoints and walking through the code line by line allows you to actually WATCH it execute. Visualizing what your code does will let you see why it behaves the way it does.

It would be well worth your time to do the tutorials on FAQ 2. A couple hours learning this skill will save you hundreds of hours of confusion in one project alone.

TOP most asked:
What does this error message mean?
FAQ 2: How do I debug
FAQ 3: How do I make Form1 talk to Form2



FAQ (Frequently Asked Questions - Updated Jan 2012

Spoiler

Was This Post Helpful? 2
  • +
  • -

#6 vbob  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 31-January 12

Re: Transform Bytes in MB if...else and speed meter

Posted 31 January 2012 - 09:01 AM

Sorry, but my point is: it don't show any bugs, it runs perfectly and smooth, but just dont do the action I prompted...
(transform bytes from MB if TotalBytes or/and ReadBytes are smaller then 1.000.000 bytes... Well, I will continue tryin' to solve it. Any new questions I'll put here...
Sorry about the questions, I'm new at programming....
Was This Post Helpful? 0
  • +
  • -

#7 vbob  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 31-January 12

Re: Transform Bytes in MB if...else and speed meter

Posted 31 January 2012 - 09:19 AM

Sorry for the flood, but I want to say that it was very helpfull, and I'm almost solving my problem. Thanks. And I more time, sorry for not beein especific.... But, I'll learn how to make a good program and solve my own small problems!!

This post has been edited by tlhIn`toq: 31 January 2012 - 09:33 AM

Was This Post Helpful? 0
  • +
  • -

#8 vbob  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 31-January 12

Re: Transform Bytes in MB if...else and speed meter

Posted 31 January 2012 - 09:37 AM

View PostCurtis Rutland, on 31 January 2012 - 08:38 AM, said:

First, you need to take a look at your logic. What you're doing is saying "if there are less than 1000 bytes, show it as kB. If there are more, show as MB." That doesn't really make sense. Also, it's easier to start at the top and work your way down.

Second, you definitely don't want to overwrite your TotalBytes and BytesRead variables. Those should probably hold your actual integral values. You need a separate value for display purposes. A string would work well, since you can include the unit (MB/kB/bytes) with it.

So, something like this:

const double MB = 1048576;
const double KB = 1024;
string total;

if (TotalBytes >= MB) {
    double t = TotalBytes / MB;
    total = string.Format("{0:0.##} MB", t);
}
else if (TotalBytes >= KB) {
    double t = TotalBytes / KB;
    total = string.Format("{0:0.##} kB", t);
}
else {
    total = string.Format("{0} bytes", TotalBytes);
}



Now, see if you can extract that into a method, so you don't have to write the same thing for BytesRead.


Worked like a charm!! Thanks!!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1