簡體   English   中英

遍歷目錄和子目錄

[英]Stepping through directories and sub-directories

我有遍歷主目錄和所有子目錄的代碼。 每個子目錄中的圖像需要根據其名稱所在的文件夾命名。

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 { }
            }

查詢時可以嘗試使用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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM