Click here to Skip to main content
13,199,852 members (65,704 online)
Rate this:
 
Please Sign up or sign in to vote.
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:

public static IEnumerable<string> GetFiles(string path)
{
    path.AsDirectory().GetFiles();
    return path; 
 
}
Posted 17-Jul-17 2:50am
Updated 17-Jul-17 3:11am
v2
Comments
Afzaal Ahmad Zeeshan 17-Jul-17 9:06am
   
Why are you returning the parameter itself?
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

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);
}
  Permalink  
Comments
Member 13302374 17-Jul-17 9:06am
   
Cheers Pete
Pete O'Hanlon 17-Jul-17 9:12am
   
Not a problem. Glad to help.
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

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

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)[^]
  Permalink  
Comments
Karthik Bangalore 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)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy |
Web01 | 2.8.171020.1 | Last Updated 17 Jul 2017
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100