【问题标题】:Deleting folder C# .net Core删除文件夹 C# .net Core
【发布时间】: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


【解决方案1】:

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

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

因为它的意思是'移动到根'。如果您想要相对路径,请忽略它。

【讨论】:

  • 是的,我现在得到了正确的路径。但我得到同样的错误:/
  • 我看到了问题所在,就是没有添加wwwroot!所以我把代码改成了 string exactPath = Path.GetFullPath("wwwroot/images/" + lastFolderName);
猜你喜欢
  • 2017-01-06
  • 2019-08-16
  • 1970-01-01
  • 2012-05-07
  • 2020-06-24
  • 2020-08-19
  • 2020-07-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多