using System;
using System.Collections;
using System.IO;
public enum SortOption
{
FileName,
Extension,
CreationTime
}
public enum OrderOption
{
UP=1,
Down=-1
}
/// <summary>
/// SortFile 的摘要说明。
/// </summary>
public class SortFile: IComparer
{
SortOption mso;
OrderOption odo;
public SortFile(SortOption so)
{
mso = so;
odo = OrderOption.UP;
}
public SortFile(SortOption so,OrderOption oo)
{
mso = so;
odo = oo;
}
int IComparer.Compare(object a, object b)
{
try
{
FileInfo fa = (FileInfo)a;
FileInfo fb = (FileInfo)b;
switch (mso)
{
case SortOption.FileName:
return ((int)odo)*String.Compare(fa.Name, fb.Name, true);
//break;
case SortOption.Extension:
return ((int)odo)*String.Compare(Path.GetExtension(fa.Name), Path.GetExtension(fb.Name), true);
//break;
case SortOption.CreationTime:
return ((int)odo)*DateTime.Compare(fa.CreationTime, fb.CreationTime);
//break;
default:
break;
}
}
catch{}
return 0;
}
public static void test(string sDir)
{
//string sDir = @ "e:\labs\csdn ";
DirectoryInfo di = new DirectoryInfo(sDir);
FileInfo[] fis = di.GetFiles();
foreach (FileInfo fi in fis)
Console.WriteLine( "{0}, {1} ", fi.Name, fi.CreationTime);
Array.Sort(fis, new SortFile(SortOption.FileName));
foreach (FileInfo fi in fis)
Console.WriteLine( "{0}, {1} ", fi.Name, fi.CreationTime);
Array.Sort(fis, new SortFile(SortOption.Extension));
foreach (FileInfo fi in fis)
Console.WriteLine( "{0}, {1} ", fi.Name, fi.CreationTime);
Array.Sort(fis, new SortFile(SortOption.CreationTime));
foreach (FileInfo fi in fis)
Console.WriteLine( "{0}, {1} ", fi.Name, fi.CreationTime);
}
}
使用Directory.GetFiles,如何按文件名,扩展名,创建时间分别进行升序或降序排序
最新推荐文章于 2024-02-02 11:48:29 发布