0

Right now, I'm using this to allow a file to be moved to our server:

filUpload.PostedFile.SaveAs(Server.MapPath("~/Images/" + filUpload.FileName));

However when I don't upload a file, it gives me an error:

System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\**\**\Documents\Visual Studio 2010\WebSites\**\Images\'.

How do I make the file upload optional so users don't have to upload a file?

Many thanks

michaelmcgurk
  • 6,367
  • 23
  • 94
  • 190

1 Answers1

0

Just check if filUpload.FileName is not empty. Only upload if it isn't.

.NET 4.0:

if(!string.IsNullOrWhiteSpace(filUpload.FileName))
{
  filUpload.PostedFile.SaveAs(Server.MapPath("~/Images/" + filUpload.FileName));
}

.NET < 4.0:

if(!string.IsNullOrEmpty(filUpload.FileName))
{
  filUpload.PostedFile.SaveAs(Server.MapPath("~/Images/" + filUpload.FileName));
}
Oded
  • 489,969
  • 99
  • 883
  • 1,009