Eri*_*ard 16 c# asp.net asp.net-mvc file-io asp.net-mvc-5
查看代码:
@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>
}
Run Code Online (Sandbox Code Playgroud)
控制器代码:
[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";
}
}
Run Code Online (Sandbox Code Playgroud)
如果它表示if(File.Exists)和File.Delete,则代码下面有波浪线.所以我想弄清楚我需要什么语法来删除thif文件.
这是我在控制器中的代码的屏幕截图:

UPPDATE:我已经有了代码工作,并在我的博客上创建了一个简单的代码示例,说明了我是如何工作的以及这个想法是如何产生的. http://httpjunkie.com/2014/724/mvc-5-image-upload-delete/
Dam*_*ith 59
使用 Request.MapPath
string fullPath = Request.MapPath("~/Images/Cakes/" + photoName);
if (System.IO.File.Exists(fullPath))
{
System.IO.File.Delete(fullPath);
}
Run Code Online (Sandbox Code Playgroud)
File当你使用它时,它是模棱两可的,因此是"波浪线".IDE无法解析您的意思;
System.Web.Mvc.Controller.File()
要么
尝试在MVC控制器中使用File API时,请使用完全限定名称.
我创建了这个功能
private bool RemoveFileFromServer(string path)
{
var fullPath = Request.MapPath(path);
if (!System.IO.File.Exists(fullPath)) return false;
try //Maybe error could happen like Access denied or Presses Already User used
{
System.IO.File.Delete(fullPath);
return true;
}
catch (Exception e)
{
//Debug.WriteLine(e.Message);
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
这是它的简单用法
RemoveFileFromServer("Content\img\ProfilePictures\User12.png");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
57873 次 |
| 最近记录: |