【问题标题】:System.IO.DirectoryNotFoundExceptionSystem.IO.DirectoryNotFoundException
【发布时间】:2016-05-17 06:51:57
【问题描述】:

我希望你们中的某个人能够帮助我解决我在代码中收到的错误。请注意,我的经验有限,因此将不胜感激! :)

当我单击“添加新产品”(btnSubmit) 时,我收到以下错误消息:

在 mscorlib.dll 中出现“System.IO.DirectoryNotFoundException”类型的异常,但未在用户代码中处理

代码: 私人无效 SaveProductPhoto() { 如果(PPhoto.PostedFile != null) { 字符串 PName = PPhoto.PostedFile.FileName.ToString(); string fileExtension = System.IO.Path.GetExtension(PPhoto.FileName);

                 }
            //Save images into Images folder
            else
            {
                PPhoto.SaveAs(Server.MapPath("~/PImg/" + PName));

            }
        }
    }

我的代码在这一行失败了:

UploadProductPhoto.SaveAs(Server.MapPath("~/ProductImages/" + PName));

【问题讨论】:

  • 在哪一行失败了?

标签: asp.net sql-server exception


【解决方案1】:

以下行不正确:

UploadProductPhoto.SaveAs(Server.MapPath("~/ProductImages/" + fileName));

这是不正确的,因为您正在使用Server.MapPath 关于不存在的路径"~/ProductImages/" + fileName

要修复它,您必须首先获取要放置图像的目录路径,然后将其与文件名结合起来,如下所示:System.Io.Path.Combine(Server.MapPath("~/ProductImages/"), fileName)

注意 Server.MapPath 只包含"~/ProductImages/"

最后你会得到类似下面的代码。

UploadProductPhoto.SaveAs(
     System.IO.Path.Combine(Server.MapPath("~/ProductImages/"), fileName)
);

【讨论】:

  • 抱歉,笔记本电脑发帖很奇怪。它显示“在 mscorlib.dll 中发生了‘System.FormatException’类型的异常,但未在用户代码中处理。附加信息:输入字符串的格式不正确。”我在 "ProductImageUrl = "~/ProductImages/" + UploadProductPhoto.FileName, };" 后收到此消息
  • 这是另一个错误。与您问题中的第一条错误消息无关。看来您想生成 tmage 的图像 URL 然后只需使用以下行 => ProductImageUrl = string.Format("/ProductImages/{0}", UploadProductPhoto.FileName); 注意我没有使用“~”字符
  • 再次感谢您的回复!我更改了代码行,但仍然收到相同的错误消息! :(
  • 我认为你刚刚给我看的那一行不会引发异常。确保从字符串变量转换为整数是正确的。我的意思是 FormatException 可能是因为您将文本转换为整数并且文本不正确。请检查一下。
  • 嗨@CodeNotFound。我认为还可以,但我的编码能力不是最好的。我已经使用“购物车”逻辑更新了原始帖子以添加新产品?这是否有助于诊断问题。再次感谢!杰克
【解决方案2】:

请检查路径和文件是否已经存在。您可以看到您收到错误“找不到路径的一部分 '\stu-storage2\user-area\3\mj350\Desktop\CWWebsite\CWWebsite\ProductImages\stu-storage2\user-area\3\mj350\桌面\1.jpg'"

表示文件或文件路径错误

【讨论】:

    猜你喜欢
    • 2011-10-25
    • 1970-01-01
    • 2018-12-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    相关资源
    最近更新 更多