Удалить файл из wwwroot в Razor Pages ASP.NET
Как удалить правильно файлы из статической директории wwwroot в ASP.NET Razor Pages.
Имеется метод:
private IActionResult Delete(int id)
{
string fileName = "";
MySqlConnection connect = new MySqlConnection(DataBase.GetConfig());
try
{
connect.Open();
MySqlCommand cmd = new MySqlCommand("select * from exampletable where id = '" + id + "'", connect);
var reader = cmd.ExecuteReader();
reader.Read();
fileName = reader.GetString("file_name");
}
finally
{
connect.Close();
}
var fullPath = "/uploads/" + fileName; //попробывал wwwroot/uploads и ~/uploads
try
{
if (System.IO.File.Exists(fullPath))
{
System.IO.File.Delete(fullPath);
}
}
catch(Exception ex)
{
Console.WriteLine(ex+"");
Debug.WriteLine(ex+"");
}
return null;
}
Читаю название с базы, файлы правильно читает, всё проверил дебагом, но удалить пропускает сам метод. Exception ничего не показывает в выводе.
как решить?
Ответы (1 шт):
Автор решения: OYBEK RUSTAMOV
→ Ссылка
Решил: Проблема была в правильности пути.
private readonly ILogger<IndexModel> _logger;
private readonly IHostEnvironment _environment;
public DeleteModel(ILogger<IndexModel> logger, IHostEnvironment environment)
{
_logger = logger;
_environment = environment;
}
private IActionResult Delete(int id)
{
string fileName = "";
MySqlConnection connect = new MySqlConnection(DataBase.GetConfig());
try
{
connect.Open();
MySqlCommand cmd = new MySqlCommand("select * from exampletable where id = '" + id + "'", connect);
var reader = cmd.ExecuteReader();
reader.Read();
fileName = reader.GetString("file_name");
}
finally
{
connect.Close();
}
var fullPath = _environment.ContentRootPath+"/uploads/" + fileName;
try
{
if (System.IO.File.Exists(fullPath))
{
System.IO.File.Delete(fullPath);
}
}
catch(Exception ex)
{
Console.WriteLine(ex+"");
Debug.WriteLine(ex+"");
}
return null;
}