【发布时间】:2023-03-27 22:45:01
【问题描述】:
我无法删除包含所有文件的文件夹。 我收到此错误:
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");
}
【问题讨论】:
-
您是否调试并检查过
exactPath是否包含您期望的目录?而且那个目录确实存在? -
它没有,它只是在相对路径前写c://..
-
Path.GetFullPath("images/" + lastFolderName)呢? -
检查它从哪里开始变成错误的路径。不是解决方案,而是减少错误的方法:在连接文件夹/文件夹和文件时使用
Path.Combine。 -
Path.GetFullPath 有效,我现在得到了正确的路径,但我仍然得到同样的错误..
标签: c# asp.net-mvc directory