0

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];
    }
Mark Buckley
  • 75
  • 1
  • 1
  • 7
  • 2
    it's use 0 for the minimum creation date. EVERY FILE YOU HAVE will match that. – Joel Coehoorn Jun 15 '17 at 17:35
  • 1
    If you want the last written file, why don't you sort by the write date and pick the one that sorts to the top of the pile? –  Jun 15 '17 at 17:37
  • If you're only interested in one file, then why are you storing and iterating over a collection of them in the second loop in your method? – Knowledge Cube Jun 15 '17 at 17:39
  • I tried to dumb down my code for the question but I broke it – Mark Buckley Jun 15 '17 at 17:43
  • Try taking a look [here](https://stackoverflow.com/q/1179970/3775798) for some ideas. – Knowledge Cube Jun 15 '17 at 17:52
  • @Christopher My directory has multiple files each with a unique identifier in the name but there's multiple files with the same identifiers, im trying to get the newest file for each of them, any idea's? – Mark Buckley Jun 15 '17 at 18:01

2 Answers2

1

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

Belgi
  • 14,542
  • 22
  • 58
  • 68
0

Why not use Linq and order by the date?

files.OrderBy(x => x.CreationDate)
jdmdevdotnet
  • 1
  • 2
  • 19
  • 50