How to get latest files in C#

Posted by Newbie on Stack Overflow See other posts from Stack Overflow or by Newbie
Published on 2010-05-04T07:23:56Z Indexed on 2010/05/04 7:28 UTC
Read the original article Hit count: 160

Filed under:

I have some files with same name but with different dates. Basically we are finding the files with most recent dates

The file patterns are

<FileNames><YYYYMMDD><FileExtension>

e.g. test_20100506.xls indicates

<FileNames> = test_
<YYYYMMDD> = 20100506
<FileExtension> = .xls

Now in the source folder, the files are

standardization_20100503.xls, standardization_20100504.xls, standardization_20100305.xls, replacement_20100505.xls

As can be seen that, standardization_.xls are 3 in numbers but replacement_.xls is only 1.

The output will be a list of file names whose content will be

standardization_20100504.xls and replacement_20100505.xls

Because among all the standardization_.xls is the most recent one and replacement_.xls is also the same.

I have tried with my own logic but somehow failed.

My idea is as under

private static void GetLatestFiles(ref List<FileInfo> validFiles)
        {
            List<FileInfo> validFilesTemp = new List<FileInfo>();
            for (int i = 0; i < validFiles.Count; i++)
            {
                for (int j = i+1; j < validFiles.Count; j++)
                {
                    string getFileTextX = ExtractText(validFiles[i].Name);
                    string getFileTextY = ExtractText(validFiles[j].Name);
                    if (getFileTextX == getFileTextY)
                    {
                        int getFileDatesX = Convert.ToInt32(ExtractNumbers(validFiles[i].Name));
                        int getFileDatesY = Convert.ToInt32(ExtractNumbers(validFiles[j].Name));

                        if (getFileDatesX > getFileDatesY)
                        {
                            validFilesTemp.Add(validFiles[i]);
                        }
                        else
                        {
                            validFilesTemp.Add(validFiles[j]);
                        }
                    }
                }
            }

            validFiles.Clear();
            validFiles = validFilesTemp;
        }

The ExtractNumbers is:

public static string ExtractNumbers(string expr)
        {
            return string.Join(null, System.Text.RegularExpressions.Regex.Split(expr, "[^\\d]"));
        }

and the ExtractText is

public static string ExtractText(string expr)
        {
            return string.Join(null, System.Text.RegularExpressions.Regex.Split(expr, "[\\d]"));
        }

I am using c#3.0 and framework 3.5

Help needed .. it's very urgent

Thanks .

© Stack Overflow or respective owner

Related posts about c#3.0