【发布时间】:2020-07-26 08:26:48
【问题描述】:
您好,我的控制器中有一个方法,如下所示。
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UploadImage(int? id)
{
if (id == null)
return HttpNotFound();
Component c = db.Components.Find((int)id);
HttpPostedFileBase photo = Request.Files["image"];
if (photo != null && photo.ContentLength > 0)
{
var filename = IGT.imagePath + "\\Components\\" + id.ToString() + ".jpg";
photo.SaveAs(filename);
c.Image_Url = IGT.baseUrl + "/Content/images/Components/" + id.ToString() + ".jpg";
db.SaveChanges();
}
else
{
if (Request["imageurl"] != null && Request["imageurl"].Length > 0)
{
// download this file
WebClient wc = new WebClient();
wc.DownloadFile(Request["imageurl"], IGT.imagePath + "\\Components\\" + id.ToString() + ".jpg");
c.Image_Url = IGT.baseUrl + "/Content/images/Components/" + id.ToString() + ".jpg";
db.SaveChanges();
}
}
HttpPostedFileBase reference = Request.Files["referencefile"];
if (reference != null && reference.ContentLength > 0)
{
// Upload the origin file and create a URL
var filename = IGT.contentPath + "\\uploads\\Comp-" + id.ToString() + "-" + System.IO.Path.GetFileName(reference.FileName);
reference.SaveAs(filename);
c.Reference_Url = IGT.baseUrl + "/Content/uploads/Comp-" + id.ToString() + "-" + System.IO.Path.GetFileName(reference.FileName);
db.SaveChanges();
}
return RedirectToAction("Edit", new { id = id });
}
但目前当它到达时
photo.SaveAs(filename);
我收到错误消息
System.IO.DirectoryNotFoundException: '找不到路径的一部分'C:\Users\chris\Source\Repos\inventory2.0\PIC_Program_1.0\Content\images\Components\498.jpg
如何创建一个 try catch 块,以便如果 IIS Express 中不存在该文件夹,它会创建它?
【问题讨论】:
标签: c# asp.net-mvc iis error-handling try-catch