【问题标题】:How to convert System.Collections.Generics.IENumerable <String> to string如何将 System.Collections.Generics.IENumerable <String> 转换为字符串
【发布时间】:2019-12-12 14:30:56
【问题描述】:

我想将从 Directory.EnumerateFiles 方法获得的变量转换为字符串。此变量包含一组文件夹的文件路径,其中包含 FileServer.config

 var foundFiles = Directory.EnumerateFiles(rootDirectory, "fileserver.config", 

    SearchOption.AllDirectories);
    var RepositoryName = Path.GetFileName(Path.GetDirectoryName(foundFiles));

这里的字符串rootDirectory是一个特定的路径

我有什么方法可以做到这一点?

根据我当前的实现,我在 foundFiles 变量下方收到错误“无法将 System.Collections.Generics.IENumerable 转换为字符串”。

【问题讨论】:

  • 如果有多个名为fileserver.config 的文件位于不同的子目录中会怎样?
  • 你为什么要使用 `Path.GetFileName(Path.GetDirectoryName(foundFiles));? If you want a parent directory's path you might want to use DirectoryInfo.ParentDirectory.FullPath` 来更清楚。
  • 我的要求是显示具有此“fileserver.config”的文件夹的名称
  • 但是,如果有多个文件夹都包含同名的文件,该怎么办?
  • 理想情况下,我想显示其中包含此 fileserver.config 的文件夹的文件夹名称

标签: c# file type-conversion


【解决方案1】:

我原来的答案

最初我以为您只希望有一个名为 fileserver.config 的文件,并且您想要该文件的路径 - 这可以使用 FirstOrDefault() 完成。

using System.Linq;

String firstFileMatch = Directory
    .EnumerableFiles( rootDirectory, "fileserver.config" )
    .FirstOrDefault();

if( firstFileMatch == null )
{
    throw new FileNotFoundException();
}

return Path.GetDirectoryName( Path.GetDirectoryName( fileFirstMatch ) );

新答案

在后续评论中,您说您想打印所有文件 - 所以这也很简单,使用 String.Join

using System.IO;
using System.Linq;

IEnumerable<String> fileNames = new DirectoryInfo( rootDirectoryPath )
    .EnumerableFiles( "fileServer.config", SearchOption.AllDirectories )
    .Select( fi => fi.Directory.FullName )
    .Select( dirPath => dirPath.Substring( rootDirectoryPath.Length ) );

String allNames = String.Join( "\r\n\r\n", fileNames );
MessageBox.Show( allNames );

【讨论】:

  • 但这会将 firstFileMatch 转换为 char 不是吗?
  • 无论如何我都可以简单地将 System.Collections.Generics.IENumerable 转换为字符串
  • @Devss 不。我认为您对StringIEnumerable&lt;Char&gt; 的无关事实感到困惑,但IEnumerable&lt;String&gt; 不是单个字符串值,而是可以是多个字符串values - 正如我所说,它将返回 rootDirectory 中名为 fileserver.config 的所有文件的路径 - 可以有多个具有该名称的文件。
  • 您可以推荐的任何解决方案,因为我真的卡在这里,我想通过使用字符串生成器将它们全部添加在一起,使用消息框打印出这些目录,这就是为什么我需要它是字符串格式
  • @Devss 请用你的好奇心探索FileInfo类:docs.microsoft.com/en-us/dotnet/api/…
猜你喜欢
  • 1970-01-01
  • 2012-07-04
  • 2020-11-22
  • 1970-01-01
  • 1970-01-01
  • 2020-05-20
  • 2018-12-20
  • 1970-01-01
  • 2018-11-14
相关资源
最近更新 更多