Firefox and IE read file names differently

Sep 24, 2006

In a recent web project I suddenly got an unexpected exception when I was uploading a file using a standard <asp:FileUpload /> control in ASP.NET 2.0. I’ve only been testing the website in Firefox at that point and everything worked great. The error only occurred in IE 6 and 7.

Here is a little dummy code that I’ll use to demonstrate the difference.

<asp:FileUpload runat="server" ID="txtUpload" />

 

private void Upload()

{

  string fileName = txtUpload.PostedFile.FileName;

  Response.Write(fileName);

}

If I try to upload the file C:\test.txt then the fileName variable will be set to test.txt in Firefox, but C:\test.txt in IE. The reason for the exception was that I used that filename to name the file on the server when it was uploaded and saved to disk. In Firefox that was no problem because I just added the filename to a folder path on the server like “C:\\uploads\\” + fileName. But in IE that would result in this file path C:\uploads\C:\test.txt which clearly is wrong.

I found the solution within the ASP.NET object model. It is very simple, but gave me a lot of gray hairs before figuring it out.

>

// Wrong! work only in Firefox

string fileName = txtUpload.PostedFile.FileName;

 

// Correct! Works on all browsers

string fileName = txtUpload.FileName;

Strange little quirk, but as long as you know your way around it, it’s not a big deal.

>* $4.95/month BlogEngine.net Hosting – Click Here!
Comments are closed

About the author

Mads Kristensen

Mads Kristensen
Program Manager at the Microsoft Web Platform team and founder of BlogEngine.NET.

More...

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.