none
Find newest file starting with ... RRS feed

  • Question

  • Hi folks,

    I have a directory with thousands of PDFs. All of which have a filename prefix if the customer ID. ABC123_0001.pdf, ABC123_0002.pdf....XYZ123_0001.pdf, XYZ132_0002.

    I need to be able to locate the newest file in the directory for a particular customer. 

    So say the customer ID was MAR123 and the newest file was MAR123_0059, then I want to use the customer ID as an argument to get the most recent file. 

    Dont know where to start with this.

    Any ideas ???

    John


    jppnn

    Wednesday, November 7, 2018 11:42 AM

All replies

  • I the files are in a directory, then you can load all the file names into an array

    https://docs.microsoft.com/en-us/dotnet/api/system.io.directory.getfiles?view=netframework-4.7.2

    Then you can use Linq Contains(), StartsWith() and EndsWith() functions.  

    http://www.dotnetlearners.com/linq/linq-to-string-array-with-example.aspx

    It may get you in the ballpark. 

    Wednesday, November 7, 2018 1:17 PM
  • So you cannot rely on the create or update date on the file then?

    If customer ID is the start of the file then use Directory.EnumerateFiles with a search pattern of the customerID.

    var customerId = "MAR123";
    
    var customerFiles = Directory.EnumerateFiles(searchDirectory, $"{customerId}_*.pdf");

    Then order descending assuming that the files are sequentially incrementing. The first file will be the highest number I believe but you'll need to test this code.

    var lastFile = customerFiles.OrderByDescending(s => s).FirstOrDefault();


    Michael Taylor http://www.michaeltaylorp3.net


    Wednesday, November 7, 2018 4:00 PM
    Moderator