2008-10-30 71 views
4

在沒有編寫自定義任務的情況下,是否有一個相對簡單的方法來獲取某個目錄中最新文件夾的名稱?遞歸不是必需的。我一直試圖用directory :: get-creation-time和foreach循環來做到這一點,如果聲明,yada yada。這太複雜了,我即將創建一個自定義任務。不過,我懷疑有一些簡單的方法可以通過現有的nant特性來實現。Nant - 獲取最新文件夾

回答

6

我相信你是正確的說明這樣做可能會造成混亂,特別是屬性的工作方式。如果您不想編寫自定義任務,則始終可以使用script task。例如:

<?xml version="1.0"?> 
<project name="testing" basedir="."> 

    <script language="C#" prefix="test" > 
     <code> 
      <![CDATA[ 
      [Function("find-newest-dir")] 
      public static string FindNewestDir(string startDir) { 
       string theNewestDir = string.Empty; 
       DateTime theCreateTime = new DateTime(); 
       DateTime theLastCreateTime = new DateTime(); 
       string[] theDirs = Directory.GetDirectories(startDir); 
       for (int theCurrentIdx = 0; theCurrentIdx < theDirs.Length; ++theCurrentIdx) 
       { 
        if (theCurrentIdx != 0) 
        { 
         DateTime theCurrentDirCreateTime = Directory.GetCreationTime(theDirs[ theCurrentIdx ]); 
         if (theCurrentDirCreateTime >= theCreateTime) 
         { 
          theNewestDir = theDirs[ theCurrentIdx ]; 
          theCreateTime = theCurrentDirCreateTime; 
         } 
        } 
        else 
        { 
         theNewestDir = theDirs[ theCurrentIdx ]; 
         theCreateTime = Directory.GetCreationTime(theDirs[ theCurrentIdx ]); 
        } 
       } 
       return theNewestDir; 
      } 
      ]]> 
     </code> 
    </script> 

    <property name="dir" value="" overwrite="false"/> 
    <echo message="The newest directory is: ${test::find-newest-dir(dir)}"/> 

</project> 

這樣,應該可以調用函數來獲取最新的目錄。實際功能的實現可以更改爲任何東西(優化多一點或其他),但我已經包含了一個快速參考,以便如何使用腳本任務。它產生如下輸出:

 
nant -D:dir=c:\ 

NAnt 0.85 (Build 0.85.2478.0; release; 10/14/2006) 
Copyright (C) 2001-2006 Gerry Shaw 
http://nant.sourceforge.net 

Buildfile: file:///C:/tmp/NAnt.build 
Target framework: Microsoft .NET Framework 2.0 

    [script] Scanning assembly "jdrgmbuy" for extensions. 
    [echo] The newest directory is: C:\tmp 

BUILD SUCCEEDED 

Total time: 0.3 seconds.