2014-06-10 47 views
0

我有一個包含CRM系統各種備份文件的大約30-40個文件夾的目錄。基於名稱移動最舊的文件夾(YYYYMMDD)

我開發了一個腳本,用於從遠程服務器下載文件,並將它們放置在YYYYMMDD的文件夾中,但由於空間限制,我現在需要從目錄中移動最舊的文件夾。隨着公司的IT團隊不斷移動服務器之間的文件夾,我無法使用文件夾創建日期!

什麼是最簡單的選擇?我曾看過:deleting the oldest folder by identifying from the folder name並試圖訂購這些物品,然後進行移動。

我的另一種選擇是將根目錄中的所有文件夾名稱解析到類型時間和日期列表中,選擇最低(最舊)選項,然後執行文件移動?

+3

「我看過......並試圖」 - 但?什麼不適合你?如果你不清楚你的問題與那個問題有什麼不同,它可能會被認爲是重複的。 – chiccodoro

+0

我也不明白你的問題。如果文件夾名稱是'YYYYMMDD'格式,一個簡單的「字母順序」應該可以完成這項工作...... – ChrFin

回答

1

怎麼是這樣的:

bool MoveOldestFolder(string initialFolderName, string destinationFolder) 
    { 
     // gets all top folders in your chosen location 
     var directories = System.IO.Directory.EnumerateDirectories(initialFolderName,"*", System.IO.SearchOption.TopDirectoryOnly); 

     // stores the oldest folder and it's date at the end of algorithm 
     DateTime outDate; 
     DateTime oldestDate = DateTime.MaxValue; 
     string resultFolder = string.Empty; 

     // just a temp variable 
     string tmp; 

     // using LINQ 
     directories.ToList().ForEach(p => 
     { 
      tmp = new System.IO.FileInfo(p).Name; // get the name of the current folder 
      if (DateTime.TryParseExact(tmp, 
             "yyyyMMdd", // this is case sensitive! 
             System.Globalization.CultureInfo.InvariantCulture, 
             System.Globalization.DateTimeStyles.None, 
             out outDate)) // try using folder name as date that "should" be in yyyyMMdd format - if the conversion is successful and date is older than current outDate, then store folder name and date, else nothing 
      { 
       if (outDate.Date < oldestDate.Date) 
       { 
        oldestDate = outDate; 
        resultFolder = p; 
       } 
      } 
     }); 


     // if we actually found a folder that is formatted in yyyyMMdd format 
     if (!oldestDate.Equals(DateTime.MaxValue)) 
     { 
      try 
      { 
       System.IO.Directory.Move(resultFolder, destinationFolder); 

       return true; 
      } 
      catch(Exception ex) 
      { 
       // handle the excaption 
       return false; 
      } 
     } 
     else 
     { 
      // we didnt find anything 
      return false; 
     } 
    } 

private void button1_Click(object sender, EventArgs e) 
{ 
    var initialFolderName = @"C:\initial"; 
    var destinationFolder = @"c:\dest"; 

    if (MoveOldestFolder(initialFolderName, destinationFolder)) 
    { 
     // move was successful     
    } 
    else 
    { 
     // something went wrong 
    } 
} 

其他選項是簡單地做chrfin說,但我不會在一切是在文件夾結構「花花公子」設定。文件夾名稱總是有可能不是YYYYMMDD格式,這可能會導致我想象中的一些問題。 無論如何,代碼可能看起來像這樣:

var directories = System.IO.Directory.EnumerateDirectories(initialFolderName,"*", System.IO.SearchOption.TopDirectoryOnly); 
    directories.ToList<string>().Sort(); 
    var lastDir = directories.First(); 
+0

這太好了,正是我一直在尋找的東西:) –

相關問題