循环以检查目录是否存在

本文关键字:是否 存在 检查 循环 | 更新日期: 2023-09-27 17:59:39

我是一个新手,试图根据特定月份的目录是否存在来填充Months下拉列表。

我知道目录名称将是2010年1月,2010年2月,2015年3月等等…

我目前正在使用。。。

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");
}

我该如何让这件事变得更容易?我只想循环浏览,如果目录存在,则在下拉列表中添加特定的名称。

循环以检查目录是否存在

您可以将月份存储在列表中并对其进行迭代:

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");
    }
}

或者如果你喜欢Linq:

foreach (string mounth in mounths.Where(mounth => System.IO.Directory.Exists("C:''Desktop''Month''" + mounth)))
{
    DropDownList1.Items.Add(mounth + " 2015");
}

如果你想要一些自动的东西:

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");
    }
}

这方面的另一种方法:

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, "")));

我想到的一个想法是,您可以使用类似的东西

    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");
     }
   }