Download Manager in C#

Posted by admin on August 8, 2010

Here is an example of the power of C#.  C# is probably one of the most powerful languages in the hands of a newbie that there is today. Within moments you can be writing  3d video games.

The Download Manager I’m describing below compiles fine in Visual Studio 2008 and in visual C# Express 2010. With just a few lines of code we have a download manager that can grab a file from the Internet and put it on your hard drive named the way you want  sent to the drive you want.

Download Manager written in C#

Trying to do this in C++ would have involved a mountain of code but in C# .net the classes available make this very easy to do and understand. A lot of time and money has been spent by Microsoft on the C# .net programming language.

First lets down load C# from Microsoft. You can do that here.

After Installing Visual C# onto your computer you can start programming.

Visual C# start page will come up first, you can start a new project from the start page by clicking on the new project link or you can goto > file > New Project.

After choosing new project you will be brought to a screen offering a choice of types of projects. Choose  “Windows Forms Application” .

Look to the bottom of the page and type in a project name of your choice and press OK. What will happen next is a page with a square pox will appear. This is like WYSWYG ” what you see is what you get”  type of thing as shown below.

This is your ” Form1[design] ” page. It’s on this page you will use your tools to add buttons and the like.

The next page shown here is your code page. This is where you will code the buttons and things you put on your design page. This page is called Form1.cs , this is where you will add the code to make your Downloader.

Near the top of your code page you have a bunch of using statements You now need to add a few more using statements.

using System.Net;
using System.IO;
using System.Threading;

Add these three lines above to the code page Form1.cs just below the other using statements. As in the photo below.

These days it’s not how well you program it’s how robust your libraries are. This is what makes C# .net so powerful and beneficial. These libraries may contain hundreds of thousands of lines of code. These are lines of code you don’t have to figure out how to write. When you need to do something  just spend the time to find the right  function or method as they are called in c# and plug it into your program. The only problem is that it might take you longer to figure out how to find and use a method or class then it would have to become a master at writing the code your self.

Well lets get on with the program.

The three lines we just added, system.net, system.io, and System.Threading will give us the means to download a file from the Web and save it to our local hard drive.

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;

namespace DownloadManager
{
   public partial class Form1 : Form
   {
      // The thread inside which the download happens
      private Thread thrDownload;
      // The stream of data retrieved from the web server
      private Stream strResponse;
      // The stream of data that we write to the harddrive
      private Stream strLocal;
      // The request to the web server for file information
      private HttpWebRequest webRequest;
      // The response from the web server containing information about the file
      private HttpWebResponse webResponse;
      // The progress of the download in percentage
      private static int PercentProgress;
      // The delegate which we will call from the thread to update the form
      private delegate void UpdateProgessCallback(Int64 BytesRead, Int64 TotalBytes);

      public Form1()
      {
         InitializeComponent();
      }

      private void btnDownload_Click(object sender, EventArgs e)
      {
         // Let the user know we are connecting to the server
         lblProgress.Text = "Download Starting";
         // Create a new thread that calls the Download() method
         thrDownload = new Thread(Download);
         // Start the thread, and thus call Download()
         thrDownload.Start();
      }

      private void UpdateProgress(Int64 BytesRead, Int64 TotalBytes)
      {
         // Calculate the download progress in percentages
         PercentProgress = Convert.ToInt32((BytesRead * 100) / TotalBytes);
         // Make progress on the progress bar
         prgDownload.Value = PercentProgress;
         // Display the current progress on the form
         lblProgress.Text = "Downloaded " + BytesRead + " out of " + TotalBytes + " (" + PercentProgress + "%)";
      }

      private void Download()
      {
         using (WebClient wcDownload = new WebClient())
         {
            try
            {
               // Create a request to the file we are downloading
               webRequest = (HttpWebRequest)WebRequest.Create(txtUrl.Text);
               // Set default authentication for retrieving the file
               webRequest.Credentials = CredentialCache.DefaultCredentials;
               // Retrieve the response from the server
               webResponse = (HttpWebResponse)webRequest.GetResponse();
               // Ask the server for the file size and store it
               Int64 fileSize = webResponse.ContentLength;

               // Open the URL for download
               strResponse = wcDownload.OpenRead(txtUrl.Text);
               // Create a new file stream where we will be saving the data (local drive)
               strLocal = new FileStream(txtPath.Text, FileMode.Create, FileAccess.Write, FileShare.None);

               // It will store the current number of bytes we retrieved from the server
               int bytesSize = 0;
               // A buffer for storing and writing the data retrieved from the server
               byte[] downBuffer = new byte[2048];

               // Loop through the buffer until the buffer is empty
               while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0)
               {
                  // Write the data from the buffer to the local hard drive
                  strLocal.Write(downBuffer, 0, bytesSize);
                  // Invoke the method that updates the form's label and progress bar
                  this.Invoke(new UpdateProgessCallback(this.UpdateProgress), new object[] { strLocal.Length, fileSize });
               }
            }
            finally
            {
               // When the above code has ended, close the streams
               strResponse.Close();
               strLocal.Close();
            }
         }
      }

      private void btnStop_Click(object sender, EventArgs e)
      {
         // Close the web response and the streams
         webResponse.Close();
         strResponse.Close();
         strLocal.Close();
         // Abort the thread that's downloading
         thrDownload.Abort();
         // Set the progress bar back to 0 and the label
         prgDownload.Value = 0;
         lblProgress.Text = "Download Stopped";
      }
   }
}

This program above is from Geekpedia.com a great site for learning C# and many other programming languages. This simple program shows you the power of C# and the compiler is free.  Click here for free visual C# 2010 download.

Filed under Learning C#

»

«

Comments are closed.