在 C# 中对 Directory.GetFiles 的结果进行排序

发布于 2024-11-14 10:25:25 字数 776 浏览 7 评论 0原文

我有这段代码来列出目录中的所有文件。

class GetTypesProfiler
{
    static List<Data> Test()
    {
        List<Data> dataList = new List<Data>();
        string folder = @"DIRECTORY";
        Console.Write("------------------------------------------\n");
        var files = Directory.GetFiles(folder, "*.dll");
        Stopwatch sw;
        foreach (var file in files)
        {   
            string fileName = Path.GetFileName(file);
            var fileinfo = new FileInfo(file);
            long fileSize = fileinfo.Length;
            Console.WriteLine("{0}/{1}", fileName, fileSize);
        }
        return dataList;
    }
    static void Main()
    {
         ...
    }
}

我需要根据文件大小或字母顺序打印文件信息。如何对 Directory.GetFiles() 的结果进行排序?

I have this code to list all the files in a directory.

class GetTypesProfiler
{
    static List<Data> Test()
    {
        List<Data> dataList = new List<Data>();
        string folder = @"DIRECTORY";
        Console.Write("------------------------------------------\n");
        var files = Directory.GetFiles(folder, "*.dll");
        Stopwatch sw;
        foreach (var file in files)
        {   
            string fileName = Path.GetFileName(file);
            var fileinfo = new FileInfo(file);
            long fileSize = fileinfo.Length;
            Console.WriteLine("{0}/{1}", fileName, fileSize);
        }
        return dataList;
    }
    static void Main()
    {
         ...
    }
}

I need to print out the file info based on file size or alphabetical order. How can I sort the result from Directory.GetFiles()?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

治碍 2024-11-21 10:25:25

使用 LINQ 非常容易。

按名称排序、

var sorted = Directory.GetFiles(".").OrderBy(f => f);

按大小排序、

var sorted = Directory.GetFiles(".").OrderBy(f => new FileInfo(f).Length);

Very easy with LINQ.

To sort by name,

var sorted = Directory.GetFiles(".").OrderBy(f => f);

To sort by size,

var sorted = Directory.GetFiles(".").OrderBy(f => new FileInfo(f).Length);
逐鹿 2024-11-21 10:25:25

按日期排序:(返回 FileInfo 的枚举):

Directory.GetFiles(folder, "*.dll").Select(fn => new FileInfo(fn)).
                                    OrderBy(f => f.Length);

或者按名称排序:

Directory.GetFiles(folder, "*.dll").Select(fn => new FileInfo(fn)).
                                    OrderBy(f => f.Name);

按文件名排序不需要创建 FileInfo 实例,但如果您想对文件应用不同的排序方法当然,最好先准备好 FileInfo 对象数组,然后按 LengthName OrderBy 它们财产,因此这个实现。另外,看起来您无论如何都会创建 FileInfo ,因此无论哪种情况,最好拥有一个 FileInfo 对象的集合。

抱歉,我第一次没有得到正确的答案,应该更仔细地阅读问题和文档。

To order by date: (returns an enumerable of FileInfo):

Directory.GetFiles(folder, "*.dll").Select(fn => new FileInfo(fn)).
                                    OrderBy(f => f.Length);

or, to order by name:

Directory.GetFiles(folder, "*.dll").Select(fn => new FileInfo(fn)).
                                    OrderBy(f => f.Name);

Making FileInfo instances isn't necessary for ordering by file name, but if you want to apply different sorting methods on the fly it's better to have your array of FileInfo objects in place and then just OrderBy them by Length or Name property, hence this implementation. Also, it looks like you are going to create FileInfo anyway, so it's better to have a collection of FileInfo objects either case.

Sorry I didn't get it right the first time, should've read the question and the docs more carefully.

辞取 2024-11-21 10:25:25

如果您愿意,可以在 FileInfo 对象上使用 LINQ:

var orderedFiles =  Directory.GetFiles("").Select(f=> new FileInfo(f)).OrderBy(f=> f.CreationTime)

You can use LINQ if you like, on a FileInfo object:

var orderedFiles =  Directory.GetFiles("").Select(f=> new FileInfo(f)).OrderBy(f=> f.CreationTime)
生死何惧 2024-11-21 10:25:25

试试这个,它对我有用

[System.Runtime.InteropServices.DllImport("Shlwapi.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
private static extern int StrCmpLogicalW(string psz1, string psz2);
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] arrFi = di.GetFiles("*.*");
Array.Sort(arrFi, delegate(FileInfo x, FileInfo y) { return StrCmpLogicalW(x.Name, y.Name); });

try this, it works for me

[System.Runtime.InteropServices.DllImport("Shlwapi.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
private static extern int StrCmpLogicalW(string psz1, string psz2);
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] arrFi = di.GetFiles("*.*");
Array.Sort(arrFi, delegate(FileInfo x, FileInfo y) { return StrCmpLogicalW(x.Name, y.Name); });
べ繥欢鉨o。 2024-11-21 10:25:25

如果您只需要按文件名排序并且文件标题支持升序或降序逻辑顺序,则此方法有效。我添加变量以更好地控制源和搜索模式。

Using Dir = System.IO;

string Source = yourVariable;
string SearchPattern = yourVariable;

Dir.Directory.GetFiles(Source, SearchPattern, Dir.SearchOption.AllDirectories).OrderBy(s => s).ToList();

This works if you only need to sort by file name and the file title supports the ascending or descending logical order.I add variables to have a bit more control of the source and search pattern.

Using Dir = System.IO;

string Source = yourVariable;
string SearchPattern = yourVariable;

Dir.Directory.GetFiles(Source, SearchPattern, Dir.SearchOption.AllDirectories).OrderBy(s => s).ToList();
眼泪也成诗 2024-11-21 10:25:25
// Getting Directory object
DirectoryInfo directoryInfo = new DirectoryInfo(folderName);

// getting files for this folder
FileInfo[] files = directoryInfo.GetFiles();

// Sorting using the generic Array.Sort function based on Names comparison
Array.Sort(files, delegate (FileInfo x, FileInfo y) { return String.Compare(x.Name, y.Name); });

// Sorting using the generic Array.Sort function based on the creation date of every folder
Array.Sort(files, delegate (FileInfo x, FileInfo y) { return DateTime.Compare(x.CreationTime, y.CreationTime); });

数组排序

// Getting Directory object
DirectoryInfo directoryInfo = new DirectoryInfo(folderName);

// getting files for this folder
FileInfo[] files = directoryInfo.GetFiles();

// Sorting using the generic Array.Sort function based on Names comparison
Array.Sort(files, delegate (FileInfo x, FileInfo y) { return String.Compare(x.Name, y.Name); });

// Sorting using the generic Array.Sort function based on the creation date of every folder
Array.Sort(files, delegate (FileInfo x, FileInfo y) { return DateTime.Compare(x.CreationTime, y.CreationTime); });

Array Sort

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文