【问题标题】:Getting System.IO.DirectoryNotFoundException: 'Could not find a part of the path' after folder creation获取 System.IO.DirectoryNotFoundException:创建文件夹后“找不到路径的一部分”
【发布时间】:2020-06-30 04:41:51
【问题描述】:

在文件系统中创建目录后,我收到错误 *System.IO.DirectoryNotFoundException: 'Could not find a part of the path' *。我要做的是在文件系统中创建文件夹,然后根据用户的输入向其中添加图像文件。创建目录后尝试上传图像时出现此错误。 (行: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");
    }

有什么想法吗?

【问题讨论】:

  • 标题有空格吗?
  • @JasonRoner 是的,他们可以
  • 这可能是问题,也可能不是问题,但我建议不要在目录中允许任何空格,以免头疼。所以,我会这样做: string dir = "Content/img/portfolio/" + title.Trim().Replace(" ", "_");如果用户尝试这样做,我还将努力过滤掉任何非字母数字
  • @JasonRoner 我同意你的观点,在过滤掉非字母数字的同时,我应该解决目录中没有空格的问题。我继续并实现了空间的修剪,但我仍然收到同样的错误。
  • @MDBerry 仅用于测试,您会将这些文件夹作为解决方案的一部分添加到 Visual Studio 中吗?然后尝试通过程序访问它们。我知道您想在创建后访问它们,但此测试可能有助于创建解决方案。

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


【解决方案1】:

只要改变这个:

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

【讨论】:

    【解决方案2】:

    问题在于传递给 file.SaveAs() 方法的路径是在控制器的视图文件夹内搜索 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++;
                                    }
    

    【讨论】:

    • 我遇到了类似的错误,结果是其中一个目录拼写错误,调试通常有助于找出这一点,我很难看到它,我不得不使用比较文本工具
    猜你喜欢
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 2018-06-28
    • 1970-01-01
    相关资源
    最近更新 更多