逐步浏览目录和子目录

时间:2019-04-25 06:51:05

标签: c# directory subdirectory

我有遍历主目录和 all 子目录的代码。每个子目录中的图像都必须根据其ins名称的文件夹进行重命名

C:\Users\alle\Desktop\BillingCopy\uploaded 27-02\\Batch002-190227010418829\PPA14431564096\File1.png

应重命名为

C:\Users\alle\Desktop\BillingCopy\uploaded 27-02\Batch002-190227010418829\PPA14431564096\PPA14431564096.png

我可以看到代码正在遍历所有内容,但是图像没有被重命名,而且我看不到哪里出了错

while(isTrue)
            {
                try
                {
                    //write your code here
                    string filename1 = "1.tif";
                    string newFileName = "allen.tif";

                    string[] rootFolder = Directory.GetDirectories(@"C:\Users\alle\Desktop\BillingCopy");

                    foreach(string dir in rootFolder)
                    {
                        string[] subDir1 = Directory.GetDirectories(dir);

                        foreach(string subDir in subDir1)
                        {
                            string[] batchDirList = Directory.GetDirectories(subDir);

                            foreach(string batchDir in batchDirList)
                            {
                                string[] waybillNumberDir = Directory.GetDirectories(batchDir);

                                foreach(string hawbDir in waybillNumberDir)
                                {
                                    string waybillNumber = Path.GetDirectoryName(hawbDir);

                                    string[] getFileimages = Directory.GetFiles(hawbDir);

                                    foreach(string imgInDir in getFileimages)
                                    {
                                        File.Copy(imgInDir, Path.Combine(@"C:\Users\alle\Desktop\Copy", string.Format("{0}.{1}", waybillNumber, Path.GetExtension(imgInDir))));
                                    }
                                }
                            }
                        }
                    }

                    File.Copy(Path.Combine("source file", filename1), Path.Combine("dest path", 
                        string.Format("{0}{1}", Path.GetFileNameWithoutExtension(newFileName), Path.GetExtension(newFileName))), true);
                }
                catch { }
            }

1 个答案:

答案 0 :(得分:1)

查询 时,您可以尝试使用 Linq 获得所需的数据:

   // All *.png files in all subdirectories
   string rootDir = @"C:\Users\alle\Desktop\BillingCopy";

   var agenda = Directory
    .EnumerateFiles(rootDir, "*.png", SearchOption.AllDirectories)
    .Select(file => new {
      oldName = file,
      newName = Path.Combine(
        Path.GetDirectoryName(file), 
        new DirectoryInfo(Path.GetDirectoryName(file)).Name + Path.GetExtension(file))
    })
    .ToArray();

然后我们可以移动(而不是复制)文件:

  foreach (var item in agenda)
    File.Move(item.oldName, item.newName);