首页 > 解决方案 > 删除文件夹 C# .net Core

问题描述

我无法删除包含所有文件的文件夹。我收到此错误:

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");
        }

标签: c#asp.net-mvcdirectory

解决方案


我认为这行的第一个斜线是问题所在,

string exactPath = Path.GetFullPath("/images/" + lastFolderName);

因为它的意思是“移到根”。如果您想要相对路径,请将其排除在外。


推荐阅读