Search code examples
c#listdirectorygetfiles

Copy filename from directoriy into generic list


I have a weird behavior and not sure where to go from here. I am trying to read filename from a directory and add that to the generic list of type <string>.

string path = @"C:\mydir\";

foreach (string s in Directory.GetFiles(path, "*.bak").Select(System.IO.Path.GetFileName))
{
    GenericList1.Add(s);

}

I get the error:

Object reference not set to an instance of an object.

When I Debug, I see that the variable s displays the filename as the value. Infact I can see the value when I use:

foreach (string s in Directory.GetFiles(path, "*.bak").Select(System.IO.Path.GetFileName))
{
    System.Windows.Forms.MessageBox.Show(s);           
}

Anyone has any insight where I might be going wrong here?


Solution

  •  foreach (string s in Directory.GetFiles(path, "*.bak").Select(p => Path.GetFileName(p)))
            {
                GenericList1.Add(s);
    
            }  
    

    That Select method requires a function to perform on each object. The easiest way to do this is to use a simple lambda.

    You are basically creating an anonymous method or function when using lambda. The Select method needs to know what function or action you want to take on each item of a collection. In this case you want to get the file name of each item in the collection that is returned by GetFiles method. If you want more of an explanation let me know.