Click here to Skip to main content
15,884,388 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello again
i have a folder in my pc with subfolders inside like
0001
0002
0003
0004....
inside the last folder i have txt files
how can i place to a text box the last filename from tha last folder...
i have this code
C#
var file = Directory.GetFiles("C:\\foldername", "*.*").OrderByDescending(d => new FileInfo(d).CreationTime).Select(Path.GetFileNameWithoutExtension);
            var selector = from i in file
                           orderby new FileInfo(i).CreationTime descending
                           select i;
            var last = selector.FirstOrDefault();
            textBox2.Text = last;
Posted
Comments
Stm21 24-Dec-15 13:32pm    
i try this with no success
var directory = Directory.GetDirectories("C:\\xxxx").OrderByDescending(d => new DirectoryInfo(d).CreationTime).Select(Path.GetFileNameWithoutExtension);
Sergey Alexandrovich Kryukov 24-Dec-15 13:51pm    
It all depends how you define "last". :-)
What's the problem?
—SA
Stm21 25-Dec-15 6:05am    
i want to place inside text box the last filename created inside last folder created.
with this code i get only the last folder created name.

Assuming you want them in date order, and want the "newest" file then you pretty much already have it in your "file" list:
C#
var file = Directory.GetFiles("D:\\Temp", "*.*").Select(s => new FileInfo(s)).OrderByDescending(d => d.CreationTime);
   tbResults.Text = File.ReadAllText(file.FirstOrDefault().FullName);
 
Share this answer
 
When I come across a coding "challenge" like this, I'm always looking to see ... assuming I think I'll be using similar code for similar purposes in the future ... if I can create a small "tool", and, in fact, I have written code for this task in the past.

Here's a "sketch" of how, given a valid Directory-path you can find the last, or first, file created, or modified (last written-to). I omit code to find the last (or first) Directory, since that's so easy to do, and I think you already know how to do that.

This "incomplete sketch" will compile, and get you the first created or modified file in a Directory. You can have the challenge/pleasure of extending it to return last created, or modified:
C#
// in NameSpace scope
public enum GetDateBy
{
    FirstCreated,
    LastCreated,
    FirstModified,
    LastModified
}

// in some Class' scope
private const string SearchAllString = ".";

public FileInfo GetFileDateBy(string directoryPath, bool recursive, GetDateBy datebyType)
{
    if(! Directory.Exists(directoryPath)) throw new ArgumentException("invalid directory path");

    var files = new DirectoryInfo(directoryPath).EnumerateFiles(
        SearchAllString,
        (recursive)
            ? SearchOption.AllDirectories
            : SearchOption.TopDirectoryOnly
        );

    if (files.Count() == 0) return null;

    switch (datebyType)
    {
        case GetDateBy.FirstCreated:
            return files.OrderBy(f => f.CreationTime).First();
        case GetDateBy.LastCreated:
            // for you to write
            break; // break is here so this will compile and run
        case GetDateBy.FirstModified:
            return files.OrderBy(f => f.LastWriteTime).First();
        case GetDateBy.LastModified:
            // for you to write
            break; // break is here so this will compile and run
    }

    // throw error ?
    return null;
}
A test of this code ... assume you have a TextBox named 'textBox1 on a Form with its 'MultiLine property set to 'true:
C#
private string format = "'Date:'MM/dd/yyyy\r\n'Time: 'H:mm:ss 'milliseconds:  ' FFFFFFF\r\n'UTC:  ' zzz";

string filepath = @"C:\Users\YourUserName\Desktop\SomeOuterFolder\SomeInnerFolder";

var f1 = GetFileDateBy(filepath, false, GetDateBy.FirstCreated);
if (f1 != null) 
{
    f1.Refresh();
    textBox1.AppendText(string.Format("file first created: {0}\r\n{1}\r\n\r\n",f1.Name,f1.CreationTime.ToString(format)));
}

var f3 = GetFileDateBy(filepath, false, GetDateBy.FirstModified);
if (f3 != null)
{
    f3.Refresh();
    textBox1.AppendText(string.Format("file first modified\r\n{0}\r\n{1}\r\n\r\n",f3.Name,f3.LastWriteTime.ToString(format)));
}

// you should see output like this in the TextBox:

//file first created: SomeFileName.txt
//Date:09/22/2014
//Time: 22:18:17 milliseconds:   2414408
//UTC:   +07:00
Note:

a. why use an Enum here ? I just plain like Enums, and feel they make code more readable/maintainable/expressive-of-intent, and, many times, easier to extend.

b. this method returns a FileInfo ... or ... null

c. re use of 'EnumerateFiles rather than 'GetFiles: 'EnumerateFiles may be more efficient in some cases. There's a very good CodeProject article that explores/documents this: [^].

d. you could re-write this as a static extension method, easily.

e. wonder why the LastAccessTime.Millisecond vale is some odd value, or #0: well, so do other people: [^].

f. note the use of the 'Refresh method on the FileInfo instance here: this is to ensure the file system manager has refreshed FileInfo instances it has cached: [^].
 
Share this answer
 
v3
I found it !!!!!

C#
string[] folders = Directory.GetDirectories(@"C:\\xxx\\", "*", SearchOption.AllDirectories);
            var directory = Directory.GetDirectories(@"C:\\xxx\\", "*", SearchOption.AllDirectories).OrderByDescending(d => new DirectoryInfo(d).CreationTime).Select(Path.GetFileNameWithoutExtension);
            var file = Directory.GetFiles(@"C:\\xxx\\", "*", SearchOption.AllDirectories).OrderByDescending(d => new FileInfo(d).CreationTime).Select(Path.GetFileNameWithoutExtension);
            var selector = from i in file
                           orderby new FileInfo(i).CreationTime descending
                           select i;
            var last = selector.FirstOrDefault();
            textBox2.Text = last;
 
Share this answer
 
Comments
BillWoodruff 25-Dec-15 9:28am    
Good for you ! Do keep in mind the differences between creation time, last written-to time, and, last accessed time.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900