Link to home
Start Free TrialLog in
Avatar of CraigLazar
CraigLazar

asked on

files in a foler with date as part of file name

Hi, i am using vb.net
i have a folder with load files. there is a standard naming convention
xxxccyymmdd.csv for examlple
abc20110318.csv. I need to loop thru the files and work out which is the latest file in the folder. I cannot assume to take the files modified date and use that. I need to work out which i sthe lastest file based on the data passed as apart of the file name

thanks
Avatar of GeorgeGergues
GeorgeGergues

use the Folder and FileInfo Objects to get the file name attribute

Parse the String of the Filename without the extension ,
get the last 8 chars into a string

Use the Convert Utility to get the date.

then push all those in a list , sort the list , and then reprocess the list.




Try this:

Imports System.IO
Imports System.Text.RegularExpressions

...

Dim files() As String = Directory.GetFiles("C:\temp\", "*.csv")
Dim latestFile As String = (From f In files _
                            Where Regex.IsMatch(Path.GetFileName(f), "^[a-z]{3}[0-9]{8}\.csv$") _
                            Order By Path.GetFileName(f).Substring(3) Descending).FirstOrDefault

Open in new window


I hope this helps.
BTW, the code I posted assumes the filename only contains lower case chars.  If you also have upper case chars, you need to change the Regex.IsMatch as follows:

Regex.IsMatch(Path.GetFileName(f), "^[a-z]{3}[0-9]{8}\.csv$", RegexOptions.IgnoreCase)


ASKER CERTIFIED SOLUTION
Avatar of gamarrojgq
gamarrojgq

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of CraigLazar

ASKER

thanks