Home > Software design >  Filter a (.txt) file from folder using two DateTime pickers in C#
Filter a (.txt) file from folder using two DateTime pickers in C#

Time:11-26

I have some logfiles in some directories which are .txt files and in their names they have some unique name code which are in ddMMyyy format for example BlockPanel Logs_**23112022_00**.txt the bolded block is that unique name which is a date as I said. What I want to do is filter those text files which were generated within two dates which I picked by those DatePickers.

CodePudding user response:

so what you have to do there is something like this. you can add a filter for all txt files and then get the date from the file name by the SubString method (you can pass the x and y based on your file format). and then add the condition like this.

var myFiles = Directory
    .EnumerateFiles(dir, "*.txt", SearchOption.AllDirectories)
    .Where(s =>  Convert.ToDateTime(s.Substring(x,y)) > dt1 && Convert.ToDateTime(s.Substring(x,y)) < dt2);

CodePudding user response:

Here is a "verbose" version, showing all the steps without using LINQ:

private void button1_Click(object sender, EventArgs e)
{
    DateTime dt;
    String dtFormat = "ddMMyyyy";
    String folderPath = @"C:\Users\mikes\Documents\Test\";

    DateTime dtStart = dateTimePicker1.Value.Date;
    DateTime dtStop = dateTimePicker2.Value.Date;
    if (dtStart <= dtStop)
    {                
        DirectoryInfo di = new DirectoryInfo(folderPath);                                
        foreach(FileInfo fi in di.GetFiles("*.txt"))
        {
            String[] parts = Path.GetFileNameWithoutExtension(fi.Name).Split("_".ToCharArray());
            if (parts.Length>=2)
            {
                if (DateTime.TryParseExact(parts[1], dtFormat, null, System.Globalization.DateTimeStyles.None, out dt))
                {
                    if (dt >= dtStart && dt <= dtStop)
                    {
                        // ... do something with "fi" ...
                        Console.WriteLine(fi.FullName);
                    }
                }
            }
        }                
    }
}

It assumes the filename has at least one underscore _ in it, and that the date portion is after the first _, and before the second _ (if it exists).

  • Related