创建System.IO.DirectoryNotFoundException:创建文件夹后,“找不到路径的一部分”

时间:2020-03-19 03:32:01

标签: asp.net-mvc file-upload filesystems ioexception ioerror

在文件系统中创建目录后,出现错误 * System.IO.DirectoryNotFoundException:'找不到路径的一部分'* 。我想要做的是在文件系统中创建文件夹,然后根据用户的输入向其中添加图像文件。创建目录后尝试上载图像时出现此错误。 (行:file.SaveAs(Server.MapPath(filePath));)

查看:

<div class="modal fade" id="addPortfolioModal" tabindex="-1" role="dialog" aria-labelledby="addPortfolioModalLabel" aria-hidden="true">
<div class="modal-dialog modal-xlg" role="document">
    <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title">Add Portfolio</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        @using (Html.BeginForm("AddPortfolio", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
        {
            <div class="modal-body">
                <div class="container">
                    <div class="row">
                        <div class="col-md-6 col-sm-12 modal-form-margin">
                            @Html.Label("title", "Title: ")
                        </div>
                        <div class="col-md-6 col-sm-12 modal-form-margin">
                            @Html.TextBox("title", null, new { type = "text", @class = "w-100", required = "required" })
                        </div>
                        <div class="col-md-12 col-sm-12 modal-form-margin">
                            @Html.Label("description", "Description: ")
                        </div>
                        <div class="col-md-12 col-sm-12 modal-form-margin">
                            @Html.TextArea("description", null, new { type = "text", @class = "w-100", @id = "description" })
                        </div>
                        <div class="col-md-6 col-sm-12 modal-form-margin">
                            @Html.Label("images", "Image(s): ")
                        </div>
                        <div class="col-md-6 col-sm-12 modal-form-margin">
                            <input type="file" name="imageFiles" id="imageFiles" required multiple />
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="submit" class="btn btn-primary">Add Portfolio</button>
            </div>
        }
    </div>
</div>

控制器:

[HttpPost]
    [ValidateInput(false)]
    public ActionResult AddPortfolio(string title, string description, HttpPostedFileBase[] ImageFiles)
    {
        if (!checkLoginCredentials())
        {
            return RedirectToAction("Login", "Home");
        }
        else if (ImageFiles.Count() < 1)
        {
            TempData["imagesFail"] = true;
        }
        else
        {
            string dir = "Content/img/portfolio/" + title;
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(Server.MapPath("~/" + dir));
                List<PortfolioImageModel> images = new List<PortfolioImageModel>();
                string extension = "";
                string fileName = "";
                int orderNumCounter = 1;

                int portfolioResult = siteServices.addPortfolio(title, description);
                if(portfolioResult > 0)
                {
                    int portfolioId = siteServices.getPortfolioIdByTitle(title);

                    foreach (var file in ImageFiles)
                    {
                        if (file != null)
                        {
                            if (file.ContentLength > 0)
                            {
                                if (Path.GetExtension(file.FileName).ToLower() == ".jpg" || Path.GetExtension(file.FileName).ToLower() == ".png" || Path.GetExtension(file.FileName).ToLower() == ".jpeg" || Path.GetExtension(file.FileName).ToLower() == ".gif")
                                {
                                    extension = Path.GetExtension(file.FileName);
                                    var filePath = Path.Combine(dir, file.FileName);
                                    file.SaveAs(Server.MapPath(filePath));

                                    PortfolioImageModel temp = new PortfolioImageModel();
                                    temp.setImgLoc(fileName);
                                    temp.setPortfolioId(portfolioId);
                                    temp.setOrderNum(orderNumCounter);

                                    images.Add(temp);
                                    orderNumCounter++;
                                }
                            }
                        }
                    }

                    int imagesResult = siteServices.addPortfolioImages(images);
                    if(imagesResult < 1)
                    {
                        TempData["imagesFail"] = true;
                    }
                }
                else
                {
                    TempData["databaseConnectionFail"] = true;
                }


            }
            else
            {
                TempData["portfolioExists"] = true;
            }
        }

        return RedirectToAction("Portfolio", "Admin");
    }

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

只需更改此:

 string dir = "Content/img/portfolio/" + title.Trim().Replace(" ", "_");
  if (!Directory.Exists(Server.MapPath("~/" + dir)))
    {
      //Your Code
    }

答案 1 :(得分:0)

问题是传递到file.SaveAs()方法的路径是在控制器的view文件夹中搜索filePath变量的路径。解决方法如下(将简化以后的代码:

if (Path.GetExtension(file.FileName).ToLower() == ".jpg" || Path.GetExtension(file.FileName).ToLower() == ".png" || Path.GetExtension(file.FileName).ToLower() == ".jpeg" || Path.GetExtension(file.FileName).ToLower() == ".gif")
                                {
                                    extension = Path.GetExtension(file.FileName);
                                    fileName = file.FileName;
                                    file.SaveAs(Server.MapPath("../" + dir + "/" + fileName));

                                    PortfolioImageModel temp = new PortfolioImageModel();
                                    temp.setImgLoc(dir + "/" + fileName);
                                    temp.setOrderNum(orderNumCounter);

                                    images.Add(temp);
                                    orderNumCounter++;
                                }