search files with date pattern names in c# based on date range - c#

I have some files with this pattern:
PrefixyyyyMMddHHmmss.txt
That Prefix is always the same.
For example :
Prefix20120830115800.txt
Prefix20120829114200.txt
Prefix20120829134621.txt
I want to write a function to get one day and range and returns all files that their names are in input range from that day:
ReadFiles(string filesLocation, DateTime fromDate, int range)
Now I use this approach:
for (int i = 0; i <= range; i++)
{
SearchFolderForFiles(location, fromDate.AddDays(i));
}
SearchFolderForFiles(//params)
{
//…
string searchTemplate = string.Format("Prefix{0:yyyyMMdd}*.txt", date);
DirectoryInfo di = new DirectoryInfo(location);
FileInfo[] myFiles = di.GetFiles(searchTemplate);
//…
}
But I think it should be better way(specially we have range not separated days)
Thanks

You could do it with linq.
Horrible example, but you can see what i'm getting at :)
DateTime startDate = DateTime.Now;
DateTime endDate = DateTime.Now;
var myFiles = new DirectoryInfo(location).EnumerateFiles()
.Where(f => DateTime.Parse(System.IO.Path.GetFileNameWithoutExtension(f.Name).Replace("Prefix", "")) >= startDate
&& DateTime.Parse(System.IO.Path.GetFileNameWithoutExtension(f.Name).Replace("Prefix", "")) <= endDate);

Related

Loop through current month to next month in c#

I am facing a problem, logic written in my program is below
DataSet dslsip = mAE_Repo.FetchLastDayCustEmailsEquity_SIP_Content();
var ressip = (from r in dslsip.Tables[0].AsEnumerable() select r.Field<string>("emailid")).ToList();
var resdate = (from r in dslsip.Tables[0].AsEnumerable() select r.Field<DateTime>("a_confirmdatetime")).ToList();
//var datetime = DateTime.Now;
//List<string> date = new List<string>();
//List<DateTime> date = new List<DateTime>();
if (!ReferenceEquals(resdate,null) && resdate.Count>0)
{
for (int i = 0; i < resdate.Count()-1; i++)
{
if (resdate[i].Month == DateTime.Now.Month || resdate[i].Month < DateTime.Now.Month)
{
//Logic should write here
//var das = DateTime.Now.AddMonths(1).ToString("MM");
//var datet = resdate[i].AddMonths(1).ToString("MM");
}
}
}
In the above code 'resdate' variable I'm fetching the list of the dates
And the concept is I should add the month (current next month) Ex: {05-07-2021 00:00:00} I should add the (current month is 9 and next month is 10) so it should be {05-10-2021 00:00:00}
I'm not sure how to add the month only.
I'm new to coding.
Please help me in this.
Use AddMonths() function, example:
new DateTime(DateTime.Now.AddMonths(1).Year,
DateTime.Now.AddMonths(1).Month,
d.Day);
Output:
10/5/2021 12:00:00 AM
10/1/2021 12:00:00 AM
You need to change Month from date list. So, you can do it by using AddMonths() API. Used below Sample :
if (resdate[i].Month == DateTime.Now.Month || resdate[i].Month < DateTime.Now.Month)
{
//Logic should write here
var datet = new DateTime(resdate[i].Year, DateTime.Now.AddMonths(1).Month, resdate[i].Day, resdate[i].Hour, resdate[i].Minute, resdate[i].Second);
}
Here we modified only month data As you wanted.

Filtering date time range via file csv name

I have a list of csv files where the naming convention is in yyyymmddhhmm.csv
201606131800.csv
201606132000.csv
201606140100.csv
201606140300.csv
201606140500.csv
201606140700.csv
201606140800.csv
I need to do a file filtering from yesterday 7pm to today 7am if today date is 14 June 2016
I need to achieve these csv with file name range from 13 June 2016 7pm to 14 June 2016 7am
201606132000.csv
201606140100.csv
201606140300.csv
201606140500.csv
201606140700.csv
I have written select today files.
How can I do a filtering by date which include yesterday 7pm to 11:59pm?
string[] FileList = Directory.GetFiles(csvpath, DateTime.Today.ToString("yyyyMMdd") + "*.csv");
foreach (var fileName in FileList)
{
\\file process code.
}
If the File name and created DateTime are same then you can use the following code to get the List:
For example CreationTime for a file named 201606132000.csv will be 2016/06/13/ 20:00 and 201606140500.csv will be 2016/06/14/ 05:00
DateTime yesterdayTime = DateTime.Now.AddDays(-1).Date.AddHours(19);
DateTime TodayTime = DateTime.Now.Date.AddHours(7);
List<FileInfo> FilesBetween7To7 = Directory.GetFiles("your path here")
.Select(x => new FileInfo(x))
.Where(y => y.CreationTime > yesterdayTime &&
y.CreationTime < TodayTime)
.ToList();
Or You can do a comparison with the name and select files using the following snippet;
DateTime yesterdayTime = DateTime.Now.AddDays(-1).Date.AddHours(19);
DateTime TodayTime = DateTime.Now.Date.AddHours(7);
List<string> fileList = Directory.GetFiles(csvpath, "*.csv").ToList();
List<string> FilesInTheRange = new List<string>();
DateTime fileTime;
foreach (string file in fileList)
{
if (DateTime.TryParseExact(file.Replace(".csv",String.Empty), "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out fileTime))
{
if (fileTime >= yesterdayTime && fileTime <= TodayTime)
FilesInTheRange.Add(file);
}
}
FilesInTheRange will contains the required files
This is an untested code, but you would want to use TryParseExact and convert the filenames into datetime objects and compare based on your start and end datetime.
string dateTimeFormat = "yyyyMMddHHmm";
string[] FileList = Directory.GetFiles(csvpath, DateTime.Today.ToString("yyyyMMdd") + "*.csv");
int startHour = 19; // 7 PM
int endHour = 7; // 7 AM
DateTime startDT = new DateTime(DateTime.Now.Year, DateTime.Now.Month,
DateTime.Now.Day - 1, startHour, 0, 0);
DateTime endDT = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, endHour, 0, 0);
foreach (var fileName in FileList)
{
DateTime fileDT = DateTime.Min;
if(DateTime.TryParseExact(fileName, dateTimeFormat, CultureInfo.InvariantCulture, DateTimeStyle.None, out fileDT))
{
if(fileDT >= startDT && fileDT <= endDT)
{
\\file process code.
}
}
}

How to return a list of weekend dates between 2 dates

At the moment I have this code to return a table of all dates between 2 dates. How could I change this to have it only return the weekend dates.
The purpose of this is to use the weekend dates to check against column headers in a DataGridView to "grey-out" the weekends. I hope that's clear.
static public List<string> GetDates(DateTime start_date, DateTime end_date)
{
List<string> days_list = new List<string>();
for (DateTime date = start_date; date <= end_date; date = date.AddDays(1))
{
days_list.Add(date.ToShortDateString());
}
return days_list;
}
Use the DateTime.DayOfWeek property.
https://msdn.microsoft.com/en-US/library/system.datetime.dayofweek(v=vs.110).aspx
static public List<string> GetDates(DateTime start_date, DateTime end_date)
{
List<string> days_list = new List<string>();
for (DateTime date = start_date; date <= end_date; date = date.AddDays(1))
{
if (date.DayOfWeek == DayOfWeek.Sunday || date.DayOfWeek == DayOfWeek.Saturday)
days_list.Add(date.ToShortDateString());
}
return days_list;
You can create range of dates and then filter on them using DayOfWeek as #Vitor said:
static public List<DateTime> GetWeekendDates(DateTime start_date, DateTime end_date)
{
return Enumerable.Range(0, (int)((end_date- start_date).TotalDays) + 1)
.Select(n => StartDate.AddDays(n))
.Where(x=>x.DayOfWeek == DayOfWeek.Saturday
|| x.DayOfWeek == DayOfWeek.Sunday)
.ToList();
}
hope this solution will help you
DateTime startDate = new DateTime(2011,3,1);
DateTime endDate = DateTime.Now;
TimeSpan diff = endDate - startDate;
int days = diff.Days;
for (var i = 0; i <= days; i++)
{
var testDate = startDate.AddDays(i);
switch (testDate.DayOfWeek)
{
case DayOfWeek.Saturday:
case DayOfWeek.Sunday:
Console.WriteLine(testDate.ToShortDateString());
break;
}
}
in above code I am finding Saturday and Sunday between 1st March 2011 and today. So I have taken two variables called startDate and endDate. After that I have got difference between them and then via for loop I am checking that day of week is Saturday or Sunday

Get dates on certain weekday between two dates

I receive a start and end DateTime.
From this, I want to create a List<DateTime> of all the dates that are between these two dates, but only on specified weekdays, such as the Monday.
You can generate a list of dates as explained in Create an array or List of all dates between two dates:
public List<DateTime> GetDatesBetween(DateTime start, DateTime end)
{
var dates = Enumerable.Range(0, 1 + end.Subtract(start).Days)
.Select(offset => start.AddDays(offset))
.ToList();
return dates;
}
Now to filter this list to only include weekdays you're interested in is equally trivial by selecting only dates Where() the DayOfWeek property is one of the requested weekdays:
public List<DateTime> GetDatesBetween(DateTime start, DateTime end, params DayOfWeek[] weekdays)
{
bool allDays = weekdays == null || !weekdays.Any();
var dates = Enumerable.Range(0, 1 + end.Subtract(start).Days)
.Select(offset => start.AddDays(offset))
.Where(d => allDays || weekdays.Contains(d.DayOfWeek))
.ToList();
return dates;
}
Bellow function return a List<DateTime> contains all dates from startDate to endDate have given dayOfWeek:
public static List<DateTime> Get_DayofWeek_DatesBetween(DateTime startDate, DateTime endDate, DayOfWeek dayOfWeek)
{
List<DateTime> list = new List<DateTime>();
// Total dates in given range. "+ 1" include endDate
double totalDates = (endDate.Date - startDate.Date).TotalDays + 1;
// Find first "dayOfWeek" date from startDate
int i = dayOfWeek - startDate.DayOfWeek;
if (i < 0) i += 7;
// Add all "dayOfWeek" dates in given range
for (int j = i; j < totalDates; j += 7) list.Add(startDate.AddDays(j));
return list;
}

Getting all DateTimes between two 'DateTime's in C#

I have two DateTimes, and I want to get all DateTimes between these Dates. Such as, if my Dates are like 01.01.2010 - 05.01.2010, my function should return me a list of date (List), and it must contain 01.01.2010, 02.01.2010, 03.01.2010, 04.01.2010, and 05.01.2010.
I wrote a function like this. It works fine, if my dates are in a month. It won't work if my dates are like 01.01.2010 - 05.02.2010. Because the month changed, and my function can't handle it. Is there a function in C# that returns all dates between two dates? Or how can I handle month change?
public void GetAllDatesAndInitializeTickets(DateTime startingDate, DateTime endingDate)
{
List<DateTime> allDates = new List<DateTime>();
int starting = startingDate.Day;
int ending = endingDate.Day;
for (int i = starting; i <= ending; i++)
{
allDates.Add(new DateTime(startingDate.Year, startingDate.Month, i));
}
Question solved, see Tim Robinson's simple answer to use.
You can use DateTime objects directly in the loop, in place of your int. DateTime.AddDays handles month ends correctly.
for (DateTime date = startingDate; date <= endingDate; date = date.AddDays(1))
allDates.Add(date);
How about something like this?
public IEnumerable<DateTime> DateRange(DateTime fromDate, DateTime toDate)
{
return Enumerable.Range(0, toDate.Subtract(fromDate).Days + 1)
.Select(d => fromDate.AddDays(d));
}
Edit: Tested now. :)
public IEnumerable<DateTime> GetAllDatesAndInitializeTickets(DateTime startingDate, DateTime endingDate)
{
if (endingDate < startingDate)
{
throw new ArgumentException("endingDate should be after startingDate");
}
var ts = endingDate - startingDate;
for (int i = 0; i < ts.TotalDays; i++)
{
yield return startingDate.AddDays(i);
}
}
You were so close... just don't use the day, use the whole date.
static IEnumerable<DateTime> GetAllDatesAndInitializeTickets(DateTime startingDate, DateTime endingDate)
{
List<DateTime> allDates = new List<DateTime>();
for (DateTime i = startingDate; i <= endingDate; i = i.AddDays(1))
{
allDates.Add(i);
}
return allDates.AsReadOnly();
}
Given a lowerdate value and higher date value in String and a frequency as the third parameter this method should return a dictionary of dates; where the key is the start value of a date range and the value is the respective range.
This works fine if the frequency is either weekly or monthly- you can customize it as per your need.
The date values passed should be in proper format or you might need to format it using tryParseExact or something like that.
protected static Dictionary<DateTime, String> getDateRange(String lowerDate, String higherDate, String frequency)
{
DateTime startDate, endDate;
startDate = Convert.ToDateTime(lowerDate);
endDate = Convert.ToDateTime(higherDate);
Dictionary<DateTime, String> returnDict = new Dictionary<DateTime, String>();
while (frequency.Equals("weekly") ? (startDate.AddDays(7) <= endDate) : (startDate.AddMonths(1) <= endDate))
{
if (frequency.Equals("weekly"))
{
returnDict.Add(startDate, startDate + "-" + startDate.AddDays(7));
startDate = startDate.AddDays(8);
}
if (frequency.Equals("monthly"))
{
returnDict.Add(startDate, startDate + "-" + startDate.AddMonths(1));
startDate = startDate.AddMonths(1).AddDays(1);
}
}
returnDict.Add(startDate, startDate + "-" + endDate);
return returnDict;
}
The top solutions will fail if the date includes different hours. Here is a solution getting all hours and all days:
All Days:
static public List<string> get_days_between_two_dates(DateTime start_date, DateTime end_date)
{
List<string> days_list = new List<string>();
DateTime temp_start;
DateTime temp_end;
//--Normalize dates by getting rid of minues since they will get in the way when doing the loop
temp_start = new DateTime(start_date.Year, start_date.Month, start_date.Day);
temp_end = new DateTime(end_date.Year, end_date.Month, end_date.Day);
//--Example Should return
//--1-12-2014 5:59AM - 1-13-2014 6:01AM return 12 and 13
for (DateTime date = temp_start; date <= temp_end; date = date.AddDays(1))
{
days_list.Add(date.ToShortDateString());
}
return days_list;
}
All Hours:
static public List<string> get_hours_between_two_dates(DateTime start_date, DateTime end_date)
{
List<string> hours_24_list = new List<string>();
DateTime temp_start;
DateTime temp_end;
//--Normalize dates by getting rid of minutes since they will get in the way when doing the loop
temp_start = new DateTime(start_date.Year, start_date.Month, start_date.Day, start_date.Hour, 0, 0);
temp_end = new DateTime(end_date.Year, end_date.Month, end_date.Day, end_date.Hour, 0, 0);
//--Example Should return
//--5:59AM - 6:01AM return 5am and 6am
for (DateTime date = temp_start; date <= temp_end; date = date.AddHours(1))
{
hours_24_list.Add(date.ToShortTimeString());
}
return hours_24_list;
}
Based on your starting code and using the features available at the time of writing, here is a quick console app to demonstrate how to do it - use AddDays() instead:
class Program
{
static void Main(string[] args)
{
GetDates(new DateTime(2010, 1, 1), new DateTime(2010, 2, 5));
Console.ReadKey();
}
static List<DateTime> GetDates(DateTime startDate, DateTime endDate)
{
List<DateTime> dates = new List<DateTime>();
while ((startDate = startDate.AddDays(1)) < endDate)
dates.Add(startDate);
return dates;
}
}
Although I think the Enumerable.Range() answer from Matt is a nicer solution.
static IEnumerable<DateTime> GetAllDatesAndInitializeTickets(DateTime startingDate, DateTime endingDate)
{
List<DateTime> allDates = new List<DateTime>();
for (DateTime i = startingDate; i <= endingDate; i = i.AddDays(1))
{
allDates.Add(i);
}
return allDates.AsReadOnly();
}

Categories

Resources