Click here to Skip to main content
15,892,927 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
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:

C#
public static IEnumerable<string> GetFiles(string path)
{
    path.AsDirectory().GetFiles();
    return path; 

}
Posted
Updated 17-Jul-17 3:11am
v2
Comments
Afzaal Ahmad Zeeshan 17-Jul-17 9:06am    
Why are you returning the parameter itself?

Your syntax is wrong on the first line of your method. Try something like this instead:
C#
public static IEnumberable<string> GetFiles(string path)
{
  return Directory.GetFiles(path);
}
 
Share this answer
 
Comments
Member 13302374 17-Jul-17 9:06am    
Cheers Pete
Pete O'Hanlon 17-Jul-17 9:12am    
Not a problem. Glad to help.
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.

C#
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();
}

This would do the trick that you want it to do. Also note that this only returns the file names, not the directories — there is a different function in the System.IO namespace for that, look for it. :-)

Finally, just return the list (why are you returning a string? Obviously it should be a list of all the files).

Directory.GetFiles Method (String) (System.IO)[^]
 
Share this answer
 
Comments
Karthik_Mahalingam 17-Jul-17 11:00am    
5 for the explanation
Afzaal Ahmad Zeeshan 17-Jul-17 14:10pm    
Thank you, Karthik!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900