Hi, I have to read file in folder, file name example is “FileName_Process_1.xlsx, FileName_Process_2.xlsx, FileName_Process_3.xlsx”, in the end of file name, have a sequence number, wich I want to use in order to process the file, how I can sort the sequence directly from For Each, Directory.GetFiles(path)? Thank you for reply and have a nice day!
Please try this
This will order by the number
You can get all the files from the folder & iterate through them in order by passing the index to the name. Hope the following flow helps.
How about the following?
arrFiles = System.IO.Directory.GetFiles(yourPath).OrderBy(Function(f) CInt(System.Text.RegularExpressions.Regex.Match(System.IO.Path.GetFileNameWithoutExtension(f),"\d+$").Value)).ToArray()
arrFiles is string array type.
Sorry missed value while copying
This should solve
Hi, thank you for reply, is there need to loop twice? I want to try read with order directly from Directory.GetFiles
In the above flow, you can see that we don’t have to loop twice. ‘fileArray’ variable which is of type ‘array of strings’ contains all the file name obtained from directory.getfiles(“Your directory name”). We are just iterating through each array element present in ‘fileArray’.
By this iteration, you can access every single file in the specified directory & can process them accordingly.
Hi, thank you for reply, I have try it, and works, but do you mind to explain me how the order works? Thank you
Hi, thank you for reply, I have try it and works also, but do you mind to explain a bit about the shorting? thank you
but how to make sure the iteration is order by last string of filename?
So what I did is I extracted the number part from the file details using regular expressions
\d+(?=.xlsx) - This will match the number before .xlsx
And I converted extracted number to integer using cint
then in order by I gave the cint(extracted number) to do the ordering of the values returned
Hope this is clear
As you are passing the ‘index’ variable into the filename, which contains the number loop’s iteration, you can access the filename in order. This applies only if all files from ‘FileName_Process_1.xlsx’ to the ‘FileName_Process_[nth number].xlsx’ are present.
how if my file have 2 different number part? something like FileName_Process1_1, FileName_Process4_2 ? is this still works? I have try it myself and its work, but I not sure how its work
We replace the number part with ‘index’ then pass it to the file name?
This format will work…as I am chekng the number immediately after .xlsx and if there ia any other character it does not read that
Yes. In the first iteration, you’ll get FileName_Process_1.xlsx, in the second iteration FileName_Process_2.xlsx and so on.
Thank you very much for explanation, have a nice day!
Thank you very much for explanation, have a nice day
This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.