我正在创建简单的图像查看器,但我想通过LastTimeWrite对图片进行排序。我有一个OpenFileDialog来加载图片,当我选择文件夹中的图片时,则调用ProcessDirectory()。
private void ProcessDirectory()
{
FileTypes = new ArrayList();
FileTypes.Add("*.JPG");
FileTypes.Add("*.JPEG");
FileTypes.Add("*.GIF");
FileTypes.Add("*.BMP");
FileTypes.Add("*.PNG");
FileTypes.Add("*.TIF");
FileTypes.Add("*.TIFF");
string[] szFiles;
FileArray = new ArrayList();
foreach (string szType in FileTypes)
{
szFiles = Directory.GetFiles(Directory.GetCurrentDirectory(), szType);
if (szFiles.Length > 0)
FileArray.AddRange(szFiles);
//switch (SortImg)
//{
// case ("Asc"):
// FileArray.Sort();
// break;
// case("Date"):
string[] MyString = new string[szFiles.Length];
DateTime[] creationTimes = new DateTime[szFiles.Length];
for (int i = 0; i < szFiles.Length; i++)
{
creationTimes[i] = new FileInfo(szFiles[i]).LastWriteTime;
//creationTimes[i].ToString("yyyy-MM-dd HH:mm tt");
}
for (int i = 0; i < szFiles.Length; i++)
MyString[i] = Convert.ToString(creationTimes[i].ToString("yyyy-MM-dd HH:mm tt"));
FileArray.Sort();
listBox1.Items.AddRange(MyString);
FileArray.AddRange(MyString);
...
}
答案 0 :(得分:2)
我会使用稍微不同的方法(这需要C#3):
List<FileInfo> files = new List<FileInfo>();
List<string> fileTypes = new List<string>()
{
"*.jpg",
"*.jpeg",
"*.gif",
"*.bmp",
"*.png",
"*.tif",
"*.tiff"
};
DirectoryInfo dir = new DirectoryInfo(Directory.GetCurrentDirectory());
foreach (string fileType in fileTypes)
{
files.AddRange(dir.GetFiles(fileType));
}
var sortedFiles = files.OrderBy(f => f.LastWriteTime);
foreach (FileInfo file in sortedFiles)
{
// do something with the FileInfo
}
如果您使用的是C#2(因此您无法访问lambdas和Linq),它可能会显示如下:
Directory.SetCurrentDirectory(@"C:\23055329\files\desktop wallpaper");
List<FileInfo> files = new List<FileInfo>();
List<string> fileTypes = new List<string>()
{
"*.jpg",
"*.jpeg",
"*.gif",
"*.bmp",
"*.png",
"*.tif",
"*.tiff"
};
DirectoryInfo dir = new DirectoryInfo(Directory.GetCurrentDirectory());
foreach (string fileType in fileTypes)
{
files.AddRange(dir.GetFiles(fileType));
}
files.Sort(new Comparison<FileInfo>(delegate(FileInfo x, FileInfo y)
{
return x.LastWriteTime.CompareTo(y.LastWriteTime);
}));
foreach (FileInfo file in files)
{
// do something with the FileInfo
Console.WriteLine(file.ToString());
}