我在删除包含所有文件的文件夹时遇到问题。 我收到此错误:
Could not find a part of the path
我想要完成的是,从数据库中获取相对路径,然后删除包含所有文件的文件夹。
代码如下:
public IActionResult RemoveCar(string item)
{
var car = _context.CarModels.Where(x => x.Id.ToString() == item).FirstOrDefault();
var pictures = _context.Pictures.Where(x => x.CarModelId.ToString() == item).ToList();
if(pictures.Count() > 0 && pictures != null)
{
string parent = new System.IO.DirectoryInfo(pictures[0].Path).Parent.ToString();
string lastFolderName = Path.GetFileName(Path.GetDirectoryName(parent+"/"));
string exactPath = Path.GetFullPath("/images/" + lastFolderName);
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(exactPath);
// Delete this dir and all subdirs.
try
{
di.Delete(true);
}
catch (System.IO.IOException e)
{
Console.WriteLine(e.Message);
}
foreach (var pic in pictures)
{
_context.Pictures.Remove(pic);
}
}
_context.CarModels.Remove(car);
return RedirectToAction("RemoveCar");
}
最佳答案
我认为这一行的第一个斜线是问题所在,
string exactPath = Path.GetFullPath("/images/" + lastFolderName);
因为它的意思是“移动到根”。如果您想要相对路径,请将其保留。
关于c# - 删除文件夹 C# .net Core,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52893808/