简体   繁体   English

如何从C#中的文件夹获取第一个文件名

[英]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: 笔记:

  • 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. 在后一种情况下,您可能需要担心区分大小写和依赖于语言环境的排序。
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM