文件夹递归

cn_918 2016-09-04 01:36:46


var path = @"D:\File"
private void FindFilesInfo(string path)
{
foreach (string filePaht in Directory.GetFiles(path))
{
var file = new FileInfo(filePaht);
listFileInfo.Add(new CheckFileInfo { FileName = file.Name,Path = filePaht, FileEndTime = file.CreationTime});
}
foreach (string directory in Directory.GetDirectories(path))
{
FindFilesInfo(directory);
}
}


代码如上 递归得到给定文件下所有文件的绝对路径 filePaht

我想得到 path 的相对路径


listFileInfo.Add(new CheckFileInfo { FileName = file.Name,Path = "path的相对路径", FileEndTime = file.CreationTime});


如何实现.
...全文
167 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
Poopaye 2016-09-04
  • 打赏
  • 举报
回复
我写的可是rootPath,不是path。。。。
private void FindFilesInfo(string path, string rootPath = null)
{
      if(rootPath == null) rootPath = path;
      ....
      FindFilesInfo(directory, rootPath);
}
yakune 2016-09-04
  • 打赏
  • 举报
回复

var path = @"D:\File"
var FindPath = "*-*-*-*-*-*-*-*";
        private void FindFilesInfo(string path)
        {
            if (path.IndexOf(FindPath) < 0) { FindPath = path; }
            foreach (string filePaht in Directory.GetFiles(path))
            {
                var fileInfo = new FileInfo(filePaht);
                listFileInfo.Add(new CheckFileInfo { FileName = fileInfo.Name,Path = filePaht.Substring(FindPath.Length), FileEndTime = fileInfo.CreationTime});
            }
            foreach (string directory in Directory.GetDirectories(path))
            {
                FindFilesInfo(directory);
            }
        }
cn_918 2016-09-04
  • 打赏
  • 举报
回复
引用 4 楼 shingoscar 的回复:
[quote=引用 3 楼 cn_918 的回复:] [quote=引用 2 楼 shingoscar 的回复:] 错了,是保留后面的部分
filePaht = filePaht.SubString(rootPath.Length);
递归,如果这么截取的话 全是根目录.[/quote] 什么意思?[/quote] 没截取前是这样的: D:\File\A.exe D:\File\B\B.exe D:\File\B\BA\BA.exe 截取后: \A.exe \B/exe \BA/exe 我要的是: \A.exe \B\B.exe \B\BA\BA.exe
Poopaye 2016-09-04
  • 打赏
  • 举报
回复
引用 3 楼 cn_918 的回复:
[quote=引用 2 楼 shingoscar 的回复:] 错了,是保留后面的部分
filePaht = filePaht.SubString(rootPath.Length);
递归,如果这么截取的话 全是根目录.[/quote] 什么意思?
cn_918 2016-09-04
  • 打赏
  • 举报
回复
引用 2 楼 shingoscar 的回复:
错了,是保留后面的部分
filePaht = filePaht.SubString(rootPath.Length);
递归,如果这么截取的话 全是根目录.
Poopaye 2016-09-04
  • 打赏
  • 举报
回复
错了,是保留后面的部分
filePaht = filePaht.SubString(rootPath.Length);
Poopaye 2016-09-04
  • 打赏
  • 举报
回复
截断掉即可
filePaht.SubString(0, rootPath.Length);

111,129

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧