Reputation: 632
I'm having trouble deleting a folder with all files in it. I get this error:
Could not find a part of the path
What I'm trying to accomplish is, getting the relative path from the database, and then deleting that folder with all files in it.
Here is the code:
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");
}
Upvotes: 1
Views: 1009
Reputation: 3231
I think the first slash in this line is the problem,
string exactPath = Path.GetFullPath("/images/" + lastFolderName);
as it means 'move to the root'. Leave it out if you want a relative path.
Upvotes: 3