Reputation: 195
I am a newbie trying to populate a Months drop-down based on whether the directories exists for the particular month.
I know the directories names will be Jan 2010, Feb 2010, Mar 2015 and so on...
I am currently using...
if (System.IO.Directory.Exists("C:\\Desktop\\Month\\Jan\\"))
{
DropDownList1.Items.Add("Jan 2015");
}
if (System.IO.Directory.Exists("C:\\Desktop\\Month\\Feb\\"))
{
DropDownList1.Items.Add("Feb 2015");
}
if (System.IO.Directory.Exists("C:\\Desktop\\Month\\March\\"))
{
DropDownList1.Items.Add("March 2015");
}
How can I make this easier? I just want to loop through and if directory exists add particular name to the drop-down.
Upvotes: 0
Views: 1134
Reputation: 29451
You can store your months in a list and iterate over it:
List<string> months = new List<string>()
{
"Jan", "Feb", "Mar", "Apr", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"
};
foreach (string month in months)
{
if (System.IO.File.Exists("C:\\Desktop\\Month\\" + month))
{
DropDownList1.Items.Add(month + " 2015");
}
}
Or if you like Linq:
foreach (string mounth in mounths.Where(mounth => System.IO.Directory.Exists("C:\\Desktop\\Month\\" + mounth)))
{
DropDownList1.Items.Add(mounth + " 2015");
}
If you want some automatic stuff:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); // <== Or any culture you like
List<string> monthNames = new List<string>(System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.MonthGenitiveNames);
foreach (string month in months)
{
if (System.IO.Directory.Exists("C:\\Desktop\\Month\\" + month))
{
DropDownList1.Items.Add(month + " 2015");
}
}
Upvotes: 3
Reputation: 13676
Another approach on this one:
string src = @"C:\Desktop\Month\";
string[] values = { "Jan", "Feb", "March", "Apr", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"};
DropDownList1.Items.AddRange(Directory.GetDirectories(src).Where(d => months.Contains(d.Replace(src, ""))).Select(d => d.Replace(src, "")));
Upvotes: 1
Reputation: 4550
One idea that comes to my mind is that you can use something like this
List<String> wehaveadd = new List<String>();
wehaveadd.Add("Jan");
wehaveadd.Add("Feb"); // do all the months
foreach(var item in wehaveadd){
var path = "C:\\Desktop\\Month\\" + item;
if (System.IO.Directory.Exists(path))
{
DropDownList1.Items.Add(item + " 2015");
}
}
Upvotes: 0