// POST: Files/Delete?id=5
[HttpPost]
public async void Delete (int id)
{
var file = await _context.Files.SingleOrDefaultAsync(m => m.Id == id);
if (System.IO.File.Exists(/*"~" +*/file.Path))
{
System.IO.File.Delete(/*"~" +*/file.Path);
}
_context.Files.Remove(file);
await _context.SaveChangesAsync();
}
// POST: Files/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var fileModel = await _context.Files.SingleOrDefaultAsync(m => m.Id == id);
if (System.IO.File.Exists($"wwwroot{fileModel.Path}"))
{
System.IO.File.Delete($"wwwroot{fileModel.Path}");
}
_context.Files.Remove(fileModel);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
…
using Microsoft.AspNetCore.Hosting;
public class HomeController : Controller {
private ApplicationContext db;
IHostingEnvironment _appEnv;
public HomeController (ApplicationContext context, IHostingEnvironment appEnvironment) {
_context = context;
_appEnv = appEnvironment;
}
private bool RemoveFileFromServer (string path) {
string fullPath = _appEnv.WebRootPath + path;
if (!System.IO.File.Exists (fullPath)) return false;
try {
System.IO.File.Delete (fullPath);
return true;
} catch (Exception e) {
//Debug.WriteLine(e.Message);
}
return false;
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var fileModel = await _context.Files.SingleOrDefaultAsync(m => m.Id == id);
RemoveFileFromServer(fileModel.Path)
_context.Files.Remove(fileModel);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
}