How can I sort my string array from .GetFiles() in order of date last modified in asp.net-webpages?

VoidKing picture VoidKing · Apr 15, 2013 · Viewed 9k times · Source

I have seen a really close example here:

Sorting Files by date

But I am new to LINQ and couldn't get it to work (not sure I understand the DirectoryInfo or FileInfo classes).

Here are the necessary code snippets:

(When assigning the array):

string[] files = Directory.GetFiles(Server.MapPath("~/User_Saves/" + WebSecurity.CurrentUserName), "*.xml");

for(int i = 0; i < files.Length; i++)
{
    files[i] = files[i].Substring(files[i].LastIndexOf("\\") + 1);
    files[i] = files[i].Substring(0, files[i].Length - 4);
}

(That last part, i.e., the 'for loop', simply strips the path to the file and the only expected file extension, which is ".xml", of course, from the string, leaving only the clean file name).

(When writing the array):

[this snippet may not be necessary for answering this question, but just in case]

@foreach(string file in files)
{
    <p>
        <button title="Permanently delete the requisition named, &quot;@file&quot" type="button" id="@file" class="fileDelBtn">DEL</button>&nbsp;<span style="color: #000;">~</span>&nbsp;<span id="@file" class="listFile">@file</span>
    </p>
    hasSavedFiles = true;
}

Things I have tried:

string [] files = new DirectoryInfo(Server.MapPath("~/User_Saves/" + WebSecurity.CurrentUserName)).GetFiles().OrderBy(files => files.LastWriteTime).ToArray;

Fails because of this error: CS0136: A local variable named 'files' cannot be declared in this scope because it would give a different meaning to 'files', which is already used in a 'parent or current' scope to denote something else

For one, I can't understand the lambda operator, for the life of me, even after looking here: http://msdn.microsoft.com/en-us/library/bb311046.aspx (clarification on this alone, would be greatly appreciated, but is not really the main question, by any means).

Secondly, using this example, I know that DirectoryInfo() has no overloads that take 2 arguments, so I may lose my ability to "Get" only "*.xml" files, which I would love to preserve, but is probably not absolutely necessary.

As always, any help is greatly appreciated and if any further information could be of help to you, please don't hesitate to ask.

Answer

I4V picture I4V · Apr 15, 2013
var filesInOrder = new DirectoryInfo(path).GetFiles()
                        .OrderByDescending(f => f.LastWriteTime)
                        .Select(f => f.Name)
                        .ToList();