Introduction
This article shows a C# program that implements the functions required to get the size of a file from the internet. It includes one form that contains an area to type the URL, a button to get the file size, 3 labels that show file size, name and type respectively.
Background
The idea behind this project is: you have seen many download managers that contain an option to get the size of the file you are going to download. This information provides the basic idea of what the size of the file is and helps us to prioritize our downloads.
Using the Code
Using this code is pretty simple. I used Microsoft Visual C# Express Edition for this project.
The main form contains a text box where we have to type the URL. A button is used to clear the URL. The code behind Get File Size button is given below:
if (textBox1.Text == "")
{
MessageBox.Show("You have not typed the URL", "URL Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
string URL = textBox1.Text;
string filetype = URL.Substring(URL.LastIndexOf(".") + 1,
(URL.Length - URL.LastIndexOf(".") - 1));
filetypevalue.Text = filetype.ToUpper();
string filename = URL.Substring(URL.LastIndexOf("/") + 1,
(URL.Length - URL.LastIndexOf("/") - 1));
namelabel.Text = filename;
System.Net.WebRequest req = System.Net.HttpWebRequest.Create(textBox1.Text);
req.Method = "HEAD";
System.Net.WebResponse resp = req.GetResponse();
long ContentLength = 0;
long result;
if (long.TryParse(resp.Headers.Get("Content-Length"), out ContentLength))
{
string File_Size;
if (ContentLength >= 1073741824)
{
result = ContentLength / 1073741824;
kbmbgb.Text = "GB";
}
else if (ContentLength >= 1048576)
{
result = ContentLength / 1048576;
kbmbgb.Text = "MB";
}
else
{
result = ContentLength / 1024;
kbmbgb.Text = "KB";
}
File_Size = result.ToString("0.00");
sizevaluelabel.Text = File_Size;
}
}
The code behind clear URL button is:
textBox1.Clear();
Future Enhancements
This program is in its preliminary stage. You can add or remove features according to your taste.
Some of the features to add are:
- Handle all exceptions (Program now handles exceptions when users click the get file size button without typing the URL.
- Recognize the extension and display an image. For example, if the extension is .mp3, an image of an audio file is to be displayed.
History
- 18th April, 2009: Initial post