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:
private static string GetFileSize(Uri uriPath)
var webRequest = HttpWebRequest.Create(uriPath);
webRequest.Method = "HEAD";
using (var webResponse = webRequest.GetResponse())
var fileSize = webResponse.Headers.Get("Content-Length");
var fileSizeInMegaByte = Math.Round(Convert.ToDouble(fileSize) / 1024.0 / 1024.0, 2);
return fileSizeInMegaByte + " MB";
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.