Wednesday, February 27, 2013
How to download file using C#?
In some of the cases we need to download file from the Internet, In this article I am explaining-
How to download file using C#?
For this I have used WebResponse, WebRequest Classes so we need to include System.Net Namespace.To download the file from Internet we have to make request to particular object so that I have used webRequest class object. After getting the response from the server we need to handle that response so I have used webResponse class object.
For displaying downloading process I have used ProgressBar control.
Here is the code-
private void btnDownLoadFile_Click(object sender, EventArgs e)
{
WebRequest requestObj ;
WebResponse responseObj;
Stream readerData ;
Stream writerData ;
byte[] data = new byte[1024];
int count = 0;
int total = 0;
this.Text = "Downloading file .....";
string DestinationFileName= "TargetLocation";
string SourceLocation= "SourceLocation";
Application.DoEvents();
try
{
requestObj = WebRequest.Create(SourceLocation);
responseObj = requestObj.GetResponse();
readerData = responseObj.GetResponseStream();
progressBar1.Maximum = Convert.ToInt32(responseObj .ContentLength);
progressBar1.Value = 0;
total = 0;
writerData = File.Create(DestinationFileName);
while (true)
{
count = readerData .Read(data, 0, 1024);
if (count <= 0)
{
break;
}
writerData.Write(data, 0, count);
total += 1024;
if (total < progressBar1.Maximum)
progressBar1.Value = total;
Application.DoEvents();
}
readerData .Close();
writerData.Close();
MessageBox.Show("Download completed...");
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
In above code, I am making request to download file using WebRequest Class object, for that I am passing source file url to download file.
requestObj = WebRequest.Create(TargetLocation);
After making request we will get response, using this line of code-
responseObj = requestObj.GetResponse();
Now using using Stream class object I am reading and writing data to the target file.
count = readerData .Read(data, 0, 1024);
writerData.Write(data, 0, count);
Meanwhile for displaying the download process, I am showing progressbar. Based on data read and write progressbar value will be increased which will show downloading process.
Output-
Thanks
Labels:
C#,
Download,
download file,
internet,
progressbar,
stream,
webrequest,
webresponse,
Windows Forms
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment