Home Contact RSS

HttpPostedFile.FileName browser dependent behaviour

Even though these kind of variables must have some standards (may be it already has), there are differences in practise. Be careful with the FileName property of HttpPostedFile class when you want to work on a file being uploaded by visitors of your page because the FileName value that you will get on Internet Explorer and Firefox are different.

If your visitor uses Internet Explorer, you will get the local path to the file. E.g.: C:\somefile.txt. However, if your visitor uses Firefox, the FileName value that you will get will be only the file’s name. E.g.: somefile.txt.

To avoid problems, you may have the following check.

string filename = postedFile.FileName;
if (filename.IndexOf('\\') > -1)
{
    filename = filename.Substring(filename.LastIndexOf('\\') + 1);
}
else if (filename.IndexOf('/') > -1)
{
    filename = filename.Substring(filename.LastIndexOf('/') + 1);
}

Selçuk Yavuz said,

January 27, 2009 @ 14:42

Here is another way to get file name from full path :

filename = System.IO.Path.GetFileName(postedFile.FileName);

Coskun SUNALI said,

January 27, 2009 @ 20:08

Hi Selcuk,

Thank you for sharing this nice method. I did not even have any idea about that it was there :)

Regards.

RSS feed for comments on this post · TrackBack URI

Leave a Comment