Search code examples
.netfileuploadmappath

Make 'File Upload' optional in Upload Form - .NET


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


Solution

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