c# - 删除文件夹 C# .net Core

标签 c# asp.net-mvc directory

我在删除包含所有文件的文件夹时遇到问题。 我收到此错误:

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/

相关文章:

ubuntu - ubuntu终端新目录中的链接数量问题

c# - 如何在时间流逝时收集按键?

css - HTML 根据部署机器以不同方式引用我的 CSS

c# - asp.net - 按钮事件没有启动

jquery - JQGrid 列中的文本框

c# - MVC 使操作链接执行提交

javascript - 如何使用 jquery javascript 对表格中的文件夹和文件进行排序

php - 在 php 中使用 opendir() 按字母顺序排序和显示目录列表

c# - MVC 重定向到默认路由

c# - 字符串到 float 的转换 - 小数点分隔符