Mark Buckley
Mark Buckley

Reputation: 77

C# Reading newest file in directory

I't trying to get my program to read the most recent file in a directory with a few similar files and retrieve a name but its still reading all the files. If anyone knows why I'd appreciate the help :)

EDIT: Undo

here's my code:

public GetMyNames()
{
    DirectoryInfo fileDirectory = new DirectoryInfo(@"C:\user\mark\folder");
    List<string> files = new List<string>();

    int creationDate = 0;
    string CreationDate = "";

    foreach (FileInfo fileInfo in fileDirectory.GetFiles("*.txt"))
    {
        string creationTime = fileInfo.CreationTime.ToString();
        string[] bits = creationTime.Split('/', ':', ' ');
        string i = bits[0] + bits[1] + bits[2];
        int e = Int32.Parse(i);
        if (e > creationDate)
        {
            creationDate = e;

            files.Add(fileInfo.Name);
        }
    }

    foreach(string file in files)
    {
        string filePath = fileDirectory + file;
        string lines = ReadAllLines(filePath);

        foreach (string line in Lines)
        {
            Name = Array.Find(dexLines,
        element => element.StartsWith("Name", StringComparison.Ordinal));
        }

        MyName = Name[0];
    }

Upvotes: 0

Views: 127

Answers (2)

Belgi
Belgi

Reputation: 15052

Note that OrderBy runs at an order of O(nlog(n)) as it sorts the enumerable.

I suggest using Linq Max extension method, that is:

newestFile = files.Max(x => x.CreationDate);

this is more efficient (runs at an order of O(n)) and is more readable in my opinion

Upvotes: 1

jdmdevdotnet
jdmdevdotnet

Reputation: 1

Why not use Linq and order by the date?

files.OrderBy(x => x.CreationDate)

Upvotes: 0

Related Questions