4

Is there a relatively simple way in nant, without writing a custom task, to get the name of the newest folder in a certain directory? Recursion is not needed. I have been trying to do it with directory::get-creation-time and a foreach loop and if statements, yada yada. It's too complex, and I'm about to create a custom task instead. However, I suspect there is some simpler way to do it via existing nant features.

4

1 回答 1

6

I believe you're correct in stating that doing this in a pure nant fashion might pose to be messy, especially the way properties work in nant. If you don't want to write a custom task, you can always use the script task. For example:

<?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>

With this, one should be able to call the function to get the newest directory. The implementation of the actual function could be changed to be anything (optimized a bit more or whatever), but I've included a quick one for reference on how to use the script task. It produces output like the following:

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.
于 2008-10-30T18:06:21.427 回答