[英]How to convert System.Collections.Generics.IENumerable <String> to string
I want to convert a variable obtained from a Directory.EnumerateFiles method to a string .我想将从 Directory.EnumerateFiles 方法获得的变量转换为 string 。 This Variable Contains a set of file paths of folders that contain the FileServer.config in them此变量包含一组文件夹的文件路径,其中包含 FileServer.config
var foundFiles = Directory.EnumerateFiles(rootDirectory, "fileserver.config",
SearchOption.AllDirectories);
var RepositoryName = Path.GetFileName(Path.GetDirectoryName(foundFiles));
Here string rootDirectory is a particular path这里的字符串 rootDirectory 是一个特定的路径
Any way I can achieve this ?我有什么办法可以做到这一点?
As per my current implementation I get the error "Cannot convert System.Collections.Generics.IENumerable to string " underlined Right under the foundFiles variable.根据我当前的实现,我收到错误“无法将 System.Collections.Generics.IENumerable 转换为字符串”,在 foundFiles 变量下有下划线。
Originally I thought that you only expected there to be a single file named fileserver.config
and you wanted the path to that file - which can be done using FirstOrDefault()
.最初我认为您只希望有一个名为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 ) );
In a follow-up comment you said you wanted to print all of the files - so that's straightforward too, using String.Join
:在后续评论中,您说您想打印所有文件 - 所以这也很简单,使用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 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.