0
votes

I have a form on an ASP.Net MVC website where users are supposed to upload files, Here's my code:

...
if (file.ContentLength > 4194304 || file.FileName.Length <= 0)
{
     ViewBag.Error = "Invalid file format or size";
}
fileName = Path.GetFileName(file.FileName);
...
var path = Path.Combine(Server.MapPath("~/App_Data/Folder"), Model.UploadedFile);
file.SaveAs(path);

the code works fine most of the time but occasionally the following exception is thrown:

System.ArgumentException: Illegal characters in path. at System.IO.Path.CheckInvalidPathChars(String path, Boolean checkAdditional) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode) at System.Web.HttpPostedFile.SaveAs(String filename)

However I noticed that every time this exception is thrown the user was using an Android device (Sample UserAgent: Mozilla/5.0 (Linux; Android 4.4.2; ar-ae; SAMSUNG GT-I9301I Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Version/1.5 Chrome/28.0.1500.94 Mobile Safari/537.36).

I tried uploading files using my Android device and it works fine, so any ideas?

1
Did you find out what were the file names when this exception was thrown? Did you try uploading same file from your Android device?Abhijit Annaldas
well I can not upload the same file from my device since it was not uploaded from the user's device in the first place, However I'll try to edit the error logger to save the file name in the future...Mazen

1 Answers

1
votes

So the error is coming from Path.GetFileName() method. This is due to illegal characters in a file name. You can find illegal characters with method Path.GetInvalidPathChars(). So if the file name has one of those illegal characters, you can handle it.

References:

  1. Path.GetFileName Method (String): https://msdn.microsoft.com/en-us/library/system.io.path.getfilename%28v=vs.110%29.aspx
  2. Path.GetInvalidPathChars Method (): https://msdn.microsoft.com/en-us/library/system.io.path.getinvalidpathchars%28v=vs.110%29.aspx