Model.CakeIma-6ren">
gpt4 book ai didi

c# - ASP NET MVC 5 从服务器删除文件

转载 作者:可可西里 更新时间:2023-11-01 03:11:35 25 4
gpt4 key购买 nike

查看代码:

@if (File.Exists(Server.MapPath("~/Images/Cakes/" + Html.DisplayFor(modelItem => Model.CakeImage))))
{
@model TastyCakes.Models.Cakes
<form name="deletePhoto" action="/Cakes/DeletePhoto" method="post">
@Html.AntiForgeryToken()
File name of image to delete (without .jpg extension):
<input name="photoFileName" type="text" value="@Html.DisplayFor(modelItem => Model.CakeImage)" />
<input type="submit" value="Delete" class="tiny button">
</form>
} else {
<p>*File Needs to be uploaded</p>
}

Controller 代码:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DeletePhoto(string photoFileName)
{

ViewBag.deleteSuccess = "false";
var photoName = "";
photoName = photoFileName;
var fullPath = Server.MapPath("~/Images/Cakes/" + photoName);

if (File.Exists(fullPath))
{
File.Delete(fullPath);
ViewBag.deleteSuccess = "true";
}
}

在它说 if (File.Exists) AND File.Delete 的地方,代码下面有波浪线。所以我想弄清楚删除 thif 文件需要什么语法。

这是我在 Controller 中的代码的屏幕截图: enter image description here

更新:我已经让代码正常工作,并在我的博客上创建了一个简单的代码示例,说明我是如何让它工作的以及这个想法是如何产生的。 http://httpjunkie.com/2014/724/mvc-5-image-upload-delete/

最佳答案

使用Request.MapPath

string fullPath = Request.MapPath("~/Images/Cakes/" + photoName);
if (System.IO.File.Exists(fullPath))
{
System.IO.File.Delete(fullPath);
}

关于c# - ASP NET MVC 5 从服务器删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22650740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com