我似乎需要对您一直使用的代码进行一些额外的更改。下面是组合框的新代码:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
List<Files> yourNewList = Files.GetFiles();
List<String> u = new List<string>();
if (comboBox1.Text == "Month")
{
u = (from Files f in yourNewList
where DateTime.Parse(f.CreationDate.Substring(0, 10)) > DateTime.Now.AddMonths(-1)
select f.FileName).ToList();
}
else if (comboBox1.Text == "3 Month")
{
u = (from Files f in yourNewList
where DateTime.Parse(f.CreationDate.Substring(0, 10)) > DateTime.Now.AddMonths(-3)
select f.FileName).ToList();
}
else if (comboBox1.Text == "1 Year")
{
u = (from Files f in yourNewList
where DateTime.Parse(f.CreationDate.Substring(0, 10)) > DateTime.Now.AddMonths(-12)
select f.FileName).ToList();
}
listBox1.DataSource = u;
}
这是使用我创建的一个类,它存储具有文件名和创建日期/时间的文件对象:
您可以看到其中许多共享相同的创建日期(4 月的那个是我发现使用的旧 zip 文件),这是我昨天制作这些文件的目的,以帮助您。我不能欺骗 windows 从文件中提取的创建日期。
该类本身使用此代码:
public class Files
{
public string FileName { get; private set; }
public string CreationDate { get; private set; }
public List<Files> theseFiles
{
get
{
return GetFiles();
}
}
public Files(string fileName, string creationDate)
{
this.FileName = fileName;
this.CreationDate = creationDate;
}
public static List<Files> GetFiles()
{
//Gets full file names
List<String> t = Directory.GetFiles(@"C:\Users\justin\Desktop\New folder (2)\").ToList();
List<String> t2 = new List<string>();
foreach (var yyy in t)
{
t2.Add(Path.GetFileName(yyy));
}
//Creation Dates
var dirInfo = new DirectoryInfo(@"C:\Users\justin\Desktop\New folder (2)");
List<String> fct = (from f in dirInfo.GetFiles("*", SearchOption.TopDirectoryOnly)
select f.CreationTime.Date.ToShortDateString()).ToList();
List<String> y = new List<string>();
foreach (var zzz in fct)
{
y.Add(zzz);
}
//Creats a collection of the file objects for you to use
List<Files> gg = new List<Files>();
for (int x = 0; x < t2.Count(); x++)
{
//Adjusts the dates to add 0's in the off chance that they aren't there
if(DateTime.Parse(y[x]).Month < 10)
{
y[x] = "0" + y[x];
}
if(DateTime.Parse(y[x]).Day < 10)
{
y[x] = y[x].Insert(3, "0");
}
Files thefile = new Files(t2[x].ToString(), y[x].ToString());
gg.Add(thefile);
}
return gg;
}
public override string ToString()
{
return string.Format("{0} , {1}", FileName, this.CreationDate);
}
}
您需要做的就是在您的项目中添加一个名为 Files 的类,并将该代码粘贴到其中。 (请确保更改类中的目录,因为它当前指向我的文件夹)
然后将代码从上到下粘贴到表单的 .cs 页面中的 SelectedIndexChanged 方法中。
请记住,if 条件基于创建时间,这就是为什么您会看到不属于那里的文件名(例如日期为 9/11/2010 的文件名)。 (再一次,我昨天创建了所有这些文件,日期为 2011 年 4 月 4 日的文件是我从 4 月找到的较旧的 zip 文件,并将其放在文件夹中进行测试。
在两张图片中,您会看到添加了 1 个文件,根据您看到返回 gg 集合的 SS 顶部,这是有道理的。在那个 SS 中,唯一不属于昨天创建日期的文件是 2011 年 4 月 7 日的那个,这就是为什么当我选择“1 年”时它会出现。