Search code examples
c#arraysfileinfodirectoryinfo

Get Sub Directory Files and Add to String Array


I am trying to insert the full directory path as well as the file and extension into the String Array but I am not getting it, any chance someone has a better way to do this.

I am using the nested for each because there is a list of Directories below the main directory "directoryInfo" that have the files I am looking for.

string[] moveLocalFiles;
List<String> localFiles = new List<String>();
DirectoryInfo directoryInfo = new DirectoryInfo(sourceFilePath);            

try
{
    foreach (DirectoryInfo i in directoryInfo.GetDirectories())
    {                                       
       foreach(FileInfo f in i.GetFiles(".twb"))
       {
           localFiles.Add(f.ToString());
       }  


    moveLocalFiles = localFiles.ToArray();

    foreach (string filePath in moveLocalFiles)
    {
     //do something
    }
}

catch (Exception ex)
{
    throw ex;
}

Solution

  • As Dan says you're definitely missing a "*" in your filter, but more than that you should use the FullName property, like this:

    localFiles.Add(f.FullName);
    

    Also (but this could be a desired behavior) you're browsing only the first level of subdirectories of "sourceFilePath" (excluding that directory as well). And also in the sample code there's a missing bracket just before the "catch" line (but I understand this is just a sample code that you pasted here and not your real program). I hope this helps.