[英]How to take first file name from a folder in C#
I need to get the first file name from a folder. 我需要从文件夹中获取第一个文件名。 How can I get this in C#? 我如何在C#中得到它?
The code below returns all the file names: 下面的代码返回所有文件名:
DirectoryInfo di = new DirectoryInfo(imgfolderPath);
foreach (FileInfo fi in di.GetFiles())
{
if (fi.Name != "." && fi.Name != ".." && fi.Name != "Thumbs.db")
{
string fileName = fi.Name;
string fullFileName = fileName.Substring(0, fileName.Length - 4);
MessageBox.Show(fullFileName);
}
}
I need the first file name. 我需要第一个文件名。
There's a few ways you could do this: 有几种方法可以做到这一点:
You could add a break
statement after handling the first file. 您可以在处理第一个文件后添加break
语句。 This will exit the foreach loop. 这将退出foreach循环。
DirectoryInfo.GetFiles
returns an array so you can assign it to a variable and scan through the elements until you find a suitable element. DirectoryInfo.GetFiles
返回一个数组,因此您可以将其分配给变量并扫描元素,直到找到合适的元素。
Or if you are using .NET 3.5 you could look at the FirstOrDefault
method with a predicate. 或者,如果您使用的是.NET 3.5,则可以使用带有谓词的FirstOrDefault
方法。
Here's some code: 这是一些代码:
string firstFileName =
di.GetFiles()
.Select(fi => fi.Name)
.FirstOrDefault(name => name != "Thumbs.db");
If you are using .Net 4.0 you should do this instead... 如果您使用的是.Net 4.0,则应改为执行此操作...
var firstFileName = di.EnumerateFiles()
.Select(f => f.Name)
.FirstOrDefault();
... .GetFiles()
creates an array and as such must scan all files. ... .GetFiles()
创建一个数组,因此必须扫描所有文件。 .EnumerateFiles()
will return an IEnumerable<FileInfo>
so it doesn't have to do as much work. .EnumerateFiles()
将返回IEnumerable<FileInfo>
因此它不必做太多工作。 You probably won't notice mush of a difference on a local hard drive with a small number of files. 您可能不会注意到带有少量文件的本地硬盘上的差异。 But a network share, thumb drive/memory card, or huge number of files would make this obvious. 但是网络共享,拇指驱动器/存储卡或大量文件将使这一点显而易见。
FileInfo fi = di.GetFiles()[0];
Notes: 笔记:
using System.IO;
using System.Linq;
var firstFile = Path.GetFileName(Directory.GetFiles(@"c:\dir", "*.*")
.FirstOrDefault(f => !String.Equals(
Path.GetFileName(f),
"Thumbs.db",
StringComparison.InvariantCultureIgnoreCase)));
In reply to riad's comment to me: 回复riad对我的评论:
In addition to abatischchev's solution: 除了abatischchev的解决方案之外:
var file = Directory.GetFiles(@"C:\TestFolder", "*.*")
.FirstOrDefault(f => f != @"C:\TestFolder\Text1.txt");
I would add this to get the name only: 我将其添加为仅获得名称:
Console.WriteLine(file.Substring(file.LastIndexOf('\\') + 1));
Which generates the output Text2.txt
(I have three text tiles in that folder called Text1.txt, Text2.txt and text3.txt. 生成输出Text2.txt
(我在该文件夹中有三个文本磁贴,分别为Text1.txt,Text2.txt和text3.txt。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.