C# - 返回包含给定目录中所有文件名的集合 [英] C# - return a collection containing all the file names within the given directory
问题描述
我被要求返回包含给定目录中所有文件名的集合(不包括子目录) 。我试过的代码如下。它应该是正确的,因为 myPath.AsDirectory()。GetFiles()
方法返回目录包含的文件列表(不包括子目录)。
现在,我在返回旁边的路径一词下方有一条红色的波浪线。它说'不能隐含地将'string'类型转换为'Systems.Collections.Generic.IEnumerable< string>'为什么会这样?我该如何修复代码?
亲切的问候
我尝试了什么:
Hi,
I have been asked to Return a collection containing all the file names within the given directory (not including subdirectories). The code I have tried is below. It should be correct because the myPath.AsDirectory().GetFiles()
method returns a list of files contained by the directory (excluding sub-directories).
Right now, I have a red squiggly line underneath the word 'path' next to return. It says 'cannot implicitly covert type 'string' to 'Systems.Collections.Generic.IEnumerable<string>' Why is this? How can I fix the code?
Kind regards
What I have tried:
public static IEnumerable<string> GetFiles(string path)
{
path.AsDirectory().GetFiles();
return path;
}
推荐答案
您的方法的第一行语法错误。请尝试这样的事情:
Your syntax is wrong on the first line of your method. Try something like this instead:
public static IEnumberable<string> GetFiles(string path)
{
return Directory.GetFiles(path);
}
你正在做的事(具有讽刺意味)是你返回传递给函数的相同参数。 :笑:你需要做的是,你需要从目录中获取文件,System.IO拥有你完成这项任务所需的一切。
What you are doing (ironically) is that you are returning the same argument that was passed to the function. :laugh: What you need to do is, that you need to get the files from a directory and System.IO has everything that you need for this task.
public static IEnumerable<string> GetFiles(string path)
{
return path.AsDirectory().GetFiles();
// I don't know where you found this extension for string
}
// I would rewrite it to
public static IEnumerable<string> GetFiles(string path) {
return Directory.GetFiles(path).ToList();
}
这样做就可以了。另请注意,这只返回文件名,而不是目录 - 在System.IO命名空间中有一个不同的函数,查找它。 :-)
最后,只返回列表(为什么要返回一个字符串?显然它应该是所有文件的列表)。
目录.GetFiles方法(字符串)(System.IO) [ ^ ]
这篇关于C# - 返回包含给定目录中所有文件名的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!