Help Me/Question Required Help In Downloading Files Using C#

krishatg

Content Writer
I am creating a small application to download some files, I just need some code help
for the following things:

1. Checking the file size of remote HTTP file, it has to only download if the remote file is newer.
2. Downloading the files from web with progress bar (preferring multiple downloads at a time).

I am trying for c# particularly, but any help is much appreciated.
 

PrashantD

Content Writer
I could not understand your question completely, please elaborate what you actually need. Share the code and we might be able to help you better. From what I understand, you need the below mentioned stuff to work. I've included the links which can actually help you to understand it.

1) Get HTTP File Size using C# Get http:/.../File Size
2) Actually download the file: How to download a file from a URL in C#?
3) Implementing Progress Bar: How do I implement a progress bar in C#?

To understand the basic concepts of C#, take a look at Microsoft's documentation: Classes (C# Programming Guide)

Let me know if you still have any doubts, preferably with some sort of code so that we know what you're doing wrong.
 

krishatg

Content Writer
Thanks @PrashantD . Links you provided are really very helpful. Actually I am learning C# so trying different things with it.I am already done with desktop application. Now i am trying my hands on web application.
Programming guide is also very good i will try with these. If there will be any doubt i will ask you.
 

Oldwriter

Content Writer
1. Checking the file size of remote HTTP file, it has to only download if the remote file is newer.
Hello @krishatg, seems you may want to check the "Last-Modified" header against your local file's last write time.

Perhaps you can adapt something like this:

Code:
// Set local file
string localFile = "your-local-file.ext";
 
// Set remote file URI
Uri remoteFileUri = new Uri("http://your-site.com/your-remote-file.ext");
 
// Get local file DateTime
DateTime localFileDateTime = new FileInfo(localFile).LastWriteTime;
 
// Set HTTP web request
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(remoteFileUri);
 
// Set method to head
httpWebRequest.Method = "HEAD";
 
// Set HTTP web response
HttpWebResponse httpWebResponse = (HttpWebResponse)(httpWebRequest.GetResponse());
 
// Get last modified datetime
DateTime remoteFileDateTime = httpWebResponse.LastModified;
 
// Compare both dates
if(DateTime.Compare(localFileDateTime, remoteFileDateTime) < 0)
{
	// Use a new web client
	using(WebClient webClient = new WebClient())
	{
		// Download asynchronously to avoid locking current thread
		webClient.DownloadFileAsync(remoteFileUri, localFile);
	}
}
 
// Close HTTP web response
httpWebResponse.Close();
Also, remember to add the directives:
Code:
using System.Net;
using System.IO;
Hope it helps.
 
Last edited:
Top