I need to get the first file name from a folder. How can I get this in C#?
The code below returns all the file names:
DirectoryInfo di = new DirectoryInfo(imgfolderPath);
foreach开发者_Go百科 (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. This will exit the foreach loop.DirectoryInfo.GetFiles
returns an array so you can assign it to a variable and scan through the elements until you find a suitable element.Or if you are using .NET 3.5 you could look at the
FirstOrDefault
method with a predicate.
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...
var firstFileName = di.EnumerateFiles()
.Select(f => f.Name)
.FirstOrDefault();
... .GetFiles()
creates an array and as such must scan all files. .EnumerateFiles()
will return an IEnumerable<FileInfo>
so it doesn't have to do as much work. 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:
- The code throws an exception if there are no files.
- "First" is ambiguous — do you mean any file, or the first one alphabetically? In the latter case, you may need to worry about stuff like case-sensitivity and locale-dependent sorting.
In reply to riad's comment to me:
In addition to abatischchev's solution:
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.
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)));
精彩评论