Many time we need to programmatically retrieve the size of a file before downloading it from a web location or a network path. This is require to calculate the progress and/or the estimated time to download and display it to the user. For a local file it is easy, but to retrieve this information from a remote location, the implementation is little different.

Today in this small blog post, we will learn how to retrieve it dynamically using C# code. Continue reading to know about it. Code snippet has been shared in the post.

The system API class “System.Net.HttpWebRequest” allows you to retrieve the file information programmatically. The size of each file/page generally available in the header section of web response, which you can query to get it. Before getting the web response from the web request, set the method of the request to “HEAD”.

Header contains “Content-Length” property value which gives you the size of the file in bytes. This you can later calculate to convert in MB or GB. Here is the code snippet for you to refer:

I hope that the post will help you to programmatically retrieve the details/file size of the remote file. Let me know, if you have any queries. Do connect with me on Twitter, Facebook or Google+ and subscribe to my news feed to get all the relevant links on developer and consumer specific.

If you have come this far, it means that you liked what you are reading. Why not reach little more and connect with me directly on Twitter, Facebook, Google+ and LinkedIn. I would love to hear your thoughts and opinions on my articles directly. Also, don't forget to share your views and/or feedback in the comment section below.

About Me

Kunal Chowdhury is a Windows Platform Development MVP of Microsoft, a Telerik MVP, Nokia Developer Champion, Speaker in various Microsoft events, Author, passionate Blogger and a Software Engineer by profession.