C# 如何获取某文件夹的文件列表,并按文件的创建时间排序?
发布网友
发布时间:2022-04-27 12:29
我来回答
共5个回答
热心网友
时间:2023-09-19 18:26
using System.Collections.Generic;
using System.IO;
List<FileInfo> files = new List<FileInfo>();
string[] fs=System.IO.Directory.GetFiles(@"****");
foreach(string file in fs)
{
files.Add(new FileInfo(file));
}
List<FileInfo> filesOrderedDESC = files.OrderByDescending(p => p.CreationTime).ToList();
List<FileInfo> filesOrderedASC = files.OrderBy(p => p.CreationTime).ToList();
热心网友
时间:2023-09-19 18:27
建立基类
public class FIleLastTimeComparer : IComparer<FileInfo>
{
int IComparer<FileInfo>.Compare(FileInfo x, FileInfo y)
{
return y.LastWriteTime.CompareTo(x.LastWriteTime);//递减
}
}
下面是引用
DirectoryInfo dirinfo = new DirectoryInfo(path+"." + extension);
FileInfo[] Files = dirinfo.GetFiles();
Array.Sort<FileInfo>(Files, new FIleLastTimeComparer());
if (!recursive)
{
if (Files.Length > 0)
return Files[0].FullName;
else
return null;
热心网友
时间:2023-09-19 18:27
public class FileComparer : IComparer
{
public int IComparer.Compare (Object o1, Object o2)
{
FileInfo fi1 = o1 as FileInfo;
FileInfo fi2 = o2 as FileInfo;
return fi1.LastWriteTime.CompareTo(fi2.LastWriteTime);
}
}
public class MyClass
{
public FileInfo[] GetFiles(string path)
{
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] files = di.GetFiles();
FileComparer fc = new FileComparer();
Array.Sort(files, fc);
return files;
}
}
热心网友
时间:2023-09-19 18:28
public class FileComparer : IComparer
{
int IComparer.Compare(Object o1, Object o2)
{
FileInfo fi1 = o1 as FileInfo;
FileInfo fi2 = o2 as FileInfo;
return fi1.LastWriteTime.CompareTo(fi2.LastWriteTime);
}
}
public class MyClass
{
public FileInfo[] GetFiles(string path)
{
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] files = di.GetFiles();
FileComparer fc = new FileComparer();
Array.Sort(files, fc);
return files;
}
}
热心网友
时间:2023-09-19 18:28
引入命名空间
using System.IO;
using System.Collections;
public class FileComparer : IComparer
{
int IComparer.Compare(Object o1, Object o2)
{
FileInfo fi1 = o1 as FileInfo;
FileInfo fi2 = o2 as FileInfo;
return fi1.CreationTime.CompareTo(fi2.CreationTime);
}
}
public class MyClass
{
public FileInfo[] GetFiles(string path)
{
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] files = di.GetFiles();
FileComparer fc = new FileComparer();
Array.Sort(files, fc);
return files;
}
}
使用
FileInfo[] a = new MyClass().GetFiles(@"D:\data");