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);

You may also like...

3 Responses

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

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

  2. Coskun SUNALI says:

    Hi Selcuk,

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


  3. tony says:

    Thanks a loooooot for this solution!!!

Leave a Reply

Your email address will not be published. Required fields are marked *