GetDirectories按文件名排序

dv2020

会员
已加入
2020年12月18日
留言内容
19
编程经验
1-3
大家好

我正在使用Directory.GetFiles来获取文件列表,并填充数据网格。代码如下。一切正常,但是尝试获取Directory.GetFiles以文件名或降序检索列表时遇到了麻烦。

有人怎么可能的话,如果不能通过Directory.GetFiles知道的话,如何让Datagrid在加载列表时自动排序呢?

Current Code:
private void DataGridReports(string searchTxt)
        {
            DgReportList.DataSource = null;

            String[] files = Directory.GetFiles(reportDirPath, "*" + searchTxt + "*", 搜索Option.AllDirectories);

            DataTable DGRptTable = new DataTable();
            DGRptTable.Columns.Add("ID");
            DGRptTable.Columns.Add("RPT");
            DGRptTable.Columns.Add("EXT");

            for (int i = 0; i < files.Length; i++)
            {
              
                FileInfo file = new FileInfo(files[i]);
                string rptid = string.Concat(file.Name.TakeWhile((c) => c != '.'));
                string rptext = file.Extension;
                string rptname = file.Name.Replace(rptid, "").Replace(rptext, "").Replace(".", "");

                DGRptTable.Rows.Add(rptid, rptname, rptext);
            }

谢谢

影碟
 
Solution
您可以使用枚举器简化某些代码,而不是将结果放入数组中然后进行迭代。只需在访问文件时枚举文件即可:
C#:
            IEnumerator<string> files = Directory.EnumerateFiles(@"C:\Python38", "*", 搜索Option.AllDirectories).GetEnumerator();
            while (files.MoveNext())
            {
                FileInfo file = new FileInfo(files.Current);
            }
Just change the the directory back to what you had set it before. I left the Python directory in there as that's the directory i used for testing it. You'd do better to build up paths using Path.Combine, and also without the overhead of using fileinfo which is...

约翰·H

C#论坛主持人
工作人员
已加入
2011年4月23日
留言内容
1,028
地点
挪威
编程经验
10+
您可以在给列进行排序和指示的地方使用Sort方法: DataGridView.Sort方法(System.Windows.Forms)

也可以对数组进行排序,但是您应该首先获取仅包含文件名或FileInfo对象的数组。首先可以使用DirectoryInfo.GetFiles完成,其次可以使用Directory.GetFiles和Path.GetFilename。
 

跳伞

工作人员
已加入
2019年4月6日
留言内容
2,500
地点
弗吉尼亚州切萨皮克
编程经验
10+
If you already have paths as strings, I highly encourage using the various Path methods to parse the path rather than instantiating a FileInfo. The first time you access a property or method on a FileInfo instance, the framework will make an OS call to get all the information related to that object. OS calls are expensive because the framework has to cross the managed/unmanaged border to make the OS call, and then back again deliver the results of the OS call. If you parse the strings, everything stays on the managed side of the world.
 
Last edited:

羊皮

退休程序员
工作人员
已加入
2018年9月5日
留言内容
1,925
地点
英国
编程经验
10+
您可以使用枚举器简化某些代码,而不是将结果放入数组中然后进行迭代。只需在访问文件时枚举文件即可:
C#:
            IEnumerator<string> files = Directory.EnumerateFiles(@"C:\Python38", "*", 搜索Option.AllDirectories).GetEnumerator();
            while (files.MoveNext())
            {
                FileInfo file = new FileInfo(files.Current);
            }
Just change the the directory back to what you had set it before. I left the Python directory in there as that's the directory i used for testing it. You'd do better to build up paths using Path.Combine, and also without the overhead of using fileinfo which is probably not relevant for what you need, unless you plan on accessing specific attributes of each file, in which case and by all means use it. By applying the advice by 跳伞, you could do something like this with the IEnumerator<string> of files :
C#:
            while (files.MoveNext())
            {
                var fileName = Path.GetFileNameWithoutExtension(files.Current);
                var fileExt = Path.GetExtension(files.Current);
                var dirOfFile = Path.GetDirectoryName(files.Current);
                if (dirOfFile.EndsWith("Python38"))
                {
                    string newfullPath = Path.Combine(dirOfFile, string.Concat(fileName, fileExt));
                    Console.WriteLine("Path : ", newfullPath);
                }
            }
This is just to give you an example of path building using Path. As you can see, this is much more specific, and way more usable resource wise as you are only using what you need by only using Path from the System.IO namespace.

I wouldn't use a file info object unless it is necessary to access a verity of other attributes of a given file not provided by the System.IO namespace/for Path. You will need to add back in your replace method calls. Since I don't know what you're trying to do there, and I didn't add that back in.

Stupidly you can't currently call for DirectoryInfo.GetFiles ToList, but this was said to be changed in the future. If you want to go this route, you can simply add a cast to the AddRange method :
C#:
            清单<string> l = new 清单<string>();
            l.AddRange((IEnumerable<string>)files);

But if you want to sort files in code rather than on the controls as mentioned above, you will need to add a 清单<string> and add each file enumerated to it. This will allow you to call Sort on your list object. And you can also call OrderByDescending from Enumerable objects such as lists. If you want the last item in to be the first item to come out. Consider using a Stack<T>. 搜索 up the highlighted words on MSDN. Hopefully this is helpful info to you!
 
Last edited:
最佳 底部