Thursday, January 13, 2011

Given Path Not Supported on Uploads with PostedFile.FileName

Have you intermittently been experiencing issues with uploads on your ASP.NET site?
Seeing errors thrown like "The given path is not supported"?

I recently stumbled across this issue with a couple of pages. I was able to dig down and fix all of my code to handle uploads again.

It looks like the code I was formerly using to save files to my web server is no longer functioning the way it used to. Previously, I saved files something to the style of:
myFileUpload.SaveAs("C:\uploads\" & myFileUpload.PostedFile.FileName)

When I started exploring the error, I discovered that the file path being generated was:
C:\uploads\C:\Users\robfine\Desktop\myFileToUpload.txt

It seems that the function .PostedFile.FileName no longer returns just the name of the file being uploaded, but rather the entire path the file was located at on the uploader's computer.

It's an easy solution to the issue; all you need to do is use the IO.FileInfo class to extract the name of the file:
Dim myFileName as String = New IO.FileInfo(myFileUpload.PostedFile.FileName).Name
myFileUpload.SaveAs("C:\uploads\" & myFileName)


I've done a little of research and it looks like this may be linked to the browser the end user is using. Some version of IE7 and a couple other browsers throw the entire path of the file out there, while other browsers may only give the filename.

Since you never know what browser your user will be using, it's best to cast the .PostedFile.FileName result into the FileInfo class just to be on the safe side.

1 comments:

Anonymous said...

Be wary of this approach. Firstly, are you sure it will work if the filename is not a valid path on the server? Secondly, the remote user's computer could be a Mac, with a full Mac path (which Windows won't know what to do with), or Linux. In fact, if it's up to the browser, it could be hacked to something completely unexpected. It could contain symbols not valid in filenames on any system.

One approach could be to find the last slash or backslash and take all the text after that point. I'm still not sure that's safe from path escalation exploits, though, and it would still suffer from the invalid character problem.

A safer approach would be to disregard the remote filename completely and use a new one generated on the server. If you must keep the remote name, be sure you're sanitizing it thoroughly.

Post a Comment