Markpelly
Markpelly

Reputation: 39

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

Upvotes: 0

Views: 2967

Answers (3)

TheLethalCoder
TheLethalCoder

Reputation: 6744

If you want to get the full path to each Directory and File you can either use your own method just altered slightly:

foreach (DirectoryInfo i in directoryInfo.GetDirectories())
{                                       
    foreach (FileInfo f in i.GetFiles("*.twb")) //The * is a wildcard search for anything
    {
        localFiles.Add(f.FullName); //FullName returns the full path
    }
}

Or you can use the System.IO.Directory class like so:

foreach (string i in Directory.GetDirectories("path to directory"))
{                                       
    foreach (string f in Directory.GetFiles(i, "*.twb")) //The * is a wildcard search for anything
    {
        localFiles.Add(f);
    }
}

Upvotes: 0

Leonardo Spina
Leonardo Spina

Reputation: 680

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.

Upvotes: 1

Dan O&#39;Leary
Dan O&#39;Leary

Reputation: 2822

It looks like you're missing a * before .twb in the GetFiles call.

Upvotes: 0

Related Questions