Thursday, June 13, 2013

C# Code to count kbps and download files from url

using System;
using System.Text;
using System.Windows.Forms;
using System.Net;

namespace Example
{
    public partial class Form1 : Form
    {

        string FileURL = "www.google.com";//your Url

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            DownloadString(FileURL);
        }

        private void DownloadString(string URLStr)
        {
            WebClient WC = new WebClient();
            WC.DownloadProgressChanged += new DownloadProgressChangedEventHandler(WC_DownloadProgressChanged);
            WC.DownloadStringCompleted += new DownloadStringCompletedEventHandler(WC_DownloadStringCompleted);
            WC.DownloadStringAsync(new Uri(URLStr));

        }
        string Result = "";
        void WC_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            Result = e.Result;
        }

        void WC_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            //Progress Bar
            PBarCsv.Value = (int)((e.BytesReceived * 100) / e.TotalBytesToReceive);
            //Label For You File Total Byte
            LblTotByt.Text = "Total Bytes : " + e.TotalBytesToReceive.ToString();
            //Label For Remaining Bytes
            LblRemByt.Text = "Remain Bytes : " + (e.TotalBytesToReceive - e.BytesReceived).ToString();
            //Label For Current KBPS Download Speed
            lblSpeed.Text = "KBPS : " + ConvertBytes(e.BytesReceived).ToString() + " Speed";
        }

        private double ConvertBytes(long bytes)
        {
            return (bytes / 1024);
            //return (bytes / 1024f) / 1024f;
        }        

5 comments: