开发者

C#: what is the simplest way to sort the directory names and pick the most recent one?

I have a list of director开发者_运维百科ies in a parent directory. These directories will be created in a format like 00001, 00002, 00003... so that the one with the bigger trailing number is the recent one. in the above instance, it is 00003. I want to get this programmatically.

thanks for any help..


Try this:

var first = Directory.GetDirectories(@"C:\")
   .OrderByDescending(x => x).FirstOrDefault();

Obviously replace C:\ with the path of the parent directory.


.NET 2:

    private void button1_Click(object sender, EventArgs e) {
        DirectoryInfo di = new DirectoryInfo(@"C:\Windows");
        DirectoryInfo[] dirs = di.GetDirectories("*", 
            SearchOption.TopDirectoryOnly);

        Array.Sort<DirectoryInfo>(dirs, 
            new Comparison<DirectoryInfo>(CompareDirs);
    }

    int CompareDirs(DirectoryInfo a, DirectoryInfo b) {
        return a.CreationTime.CompareTo(b.CreationTime);
    }


Why not do something like this:

string[] directories = Directory.GetDirectories(@"C:\temp");
string lastDirectory = string.Empty;

if (directories.Length > 0)
{
    Array.Sort(directories);
    lastDirectory = directories[directories.Length - 1];
}


What about:

var greaterDirectory =
    Directory.GetDirectories(@"C:\")
        .Select(path => Path.GetFileName(path)) // keeps only directory name
        .Max();

or

var simplest = Directory.GetDirectories(@"C:\").Max();


Just throw the output of GetDirectories or GetFiles at a bubble sort function.

    private void SortFiles(FileSystemInfo[] oFiles)
    {
        FileSystemInfo oFileInfo = null;

        int i = 0;
        while (i + 1 < oFiles.Length)
        {
            if (string.Compare(oFiles[i].Name, oFiles[i + 1].Name) > 0)
            {
                oFileInfo = oFiles[i];
                oFiles[i] = oFiles[i + 1];
                oFiles[i + 1] = oFileInfo;
                if (i > 0)
                {
                    i--;
                }
            }
            else
            {
                i++;
            }
        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜