15

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 (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.

Mark Cooper
  • 6,738
  • 5
  • 54
  • 92
riad
  • 7,144
  • 22
  • 59
  • 70

5 Answers5

34

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");
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • oh thanks..but i was trying to declare array and blay bala.. anyway thanks – riad May 26 '10 at 11:27
  • 1
    Given that `GetFiles` enumerates all files in the directory in order to create an array, it would be more efficient to use `EnumerateFiles` in this case. For more info, see https://msdn.microsoft.com/en-us/library/wz42302f(v=vs.110).aspx – Vlad Mar 21 '17 at 03:08
9

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.

Matthew Whited
  • 22,160
  • 4
  • 52
  • 69
  • 1
    What? If you are looking for a particular file add the search string. if you are just doing a blanket get first file then if that's `thumbs.db` then that's just it. Either way `.EnumerateFiles(...)` will only return files one at a time which is really helpfull in directories with tons of files and folders. https://msdn.microsoft.com/en-us/library/system.io.directoryinfo.enumeratefiles(v=vs.110).aspx – Matthew Whited Dec 17 '15 at 13:25
  • Hi. You are right. I using this solution => http://stackoverflow.com/a/2912435/1395101 but not interesting ?! because may be returned "*.any file extension" and i need code returned first only for example .jpg file . at the end i found this solution => http://stackoverflow.com/a/3152180/1395101 – Amin Ghaderi Dec 17 '15 at 20:20
  • 1
    You wil still want to use `.EnumerateFiles(...)` if you are using .Net 4.0 or greater. – Matthew Whited Dec 18 '15 at 20:36
4
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.
tc.
  • 33,468
  • 5
  • 78
  • 96
2

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.

Henric
  • 1,380
  • 2
  • 16
  • 30
1
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)));
abatishchev
  • 98,240
  • 88
  • 296
  • 433
  • Wouldn't you have to supply the full path to the lambda to get the Where clause to work? Just curious? :) – Henric May 26 '10 at 11:38
  • Note: You don't need a separate call to Where - FirstOrDefault can accept a predicate. – Mark Byers May 26 '10 at 11:40
  • True, @Mark Byers, and I don't think the above code does what is required or am I missunderstanding something? Directory.GetFiles() returns a string containing the full paths as the file names, so you would need to take that into account in the predicate as well. – Henric May 26 '10 at 11:45
  • @Mark: `GetFiles` return `string[]`. – abatishchev May 26 '10 at 11:57
  • Yes daft you rite.its return the full path of .I just need the first file name.Could you pls guide me how can i get the only first file name? – riad May 26 '10 at 11:57
  • @abatishchev: Sorry, you're right, it doesn't return FileInfo because you used Directory instead of DirectoryInfo. – Mark Byers May 26 '10 at 11:59
  • is their any way to get the first file name..pls provide me the code – riad May 26 '10 at 11:59
  • @riad: I edited my answer to omit path and take only file's name – abatishchev May 26 '10 at 11:59
  • @abatishchev:sorry bro..its still return the full path.I just need the file name only..any other way??? – riad May 26 '10 at 12:05
  • @riad: Oops! Just forgot to add `Path.GetFileName()` to resulting file path – abatishchev May 26 '10 at 12:12