I put this in a BaseController class, from which all my controllers inherit:
// this just prefixes datetime as yyyyMMddhhmmss to the filename, to
// be use that no name collision will occur.
protected static String PrefixFName(String fname)
{
if (String.IsNullOrEmpty(fname))
{
return null;
}
else
{
return String.Format("{0}{1}",
DateTime.Now.ToString("yyyyMMddhhmmss"),
fname);
}
}
protected String SaveFile(HttpPostedFileBase file, String path)
{
if (file != null && file.ContentLength > 0)
{
if (path == null)
{
throw new ArgumentNullException("path cannot be null");
}
String relpath = String.Format("{0}/{1}", path, PrefixFName(file.FileName));
try
{
file.SaveAs(Server.MapPath(relpath));
return relpath;
}
catch (HttpException e)
{
throw new ApplicationException("Cannot save uploaded file", e);
}
}
return null;
}
Then, in the controller I do:
savedPath = SaveFile(Request.Files["logo"], somepath);