kown owl
kown owl

Reputation: 43

Adding two fileinfo[] together

FileInfo[] comList = new FileInfo[]{};
FileInfo[] files
DirectoryInfo dInfo;
string[] folderList = path.Split(',');
foreach (string folder in folderList){
    dInfo = new DirectoryInfo(folder);
    files = dInfo.GetFiles().Where(F => extensions.Contains(f.Extension.ToLower())).ToArray();
    comList.Concat(files);
}

I am trying to read multiple folders and get all the files into one FileInfo[], but after doing the concat to comList, my comList is still empty.

the path input is something like string path = "pathA,pathB,pathC" if this is not the way to do it, what is a better ways to get all the files from different directory into one.

Upvotes: 0

Views: 283

Answers (2)

Zephyr
Zephyr

Reputation: 313

According to Microsoft documentation Concat will returns a new collection without modifying existing one:

public static System.Collections.Generic.IEnumerable<TSource> Concat<TSource> (
  this System.Collections.Generic.IEnumerable<TSource> first, 
  System.Collections.Generic.IEnumerable<TSource> second);

Therefore in your scenario assigning the statement back to comList as following and you're good to go!

comList = comList.Concat(files);

Nonetheless, if you're not constraining yourself to use array for comList, you may consider to use List instead which allow us to achieve the same without redundant cast:

List<FileInfo> comList = new List<FileInfo>();
...
foreach (string folder in folderList) {
   var dInfo = new DirectoryInfo(folder);
   var files = dInfo.GetFiles().Where(f => 
                 extensions.Contains(
                   f.Extension.ToLower()));

   comList.AddRange(files);
}

Upvotes: 1

Biesi
Biesi

Reputation: 910

You need to use the return of comList.Concat(files), like:

comList = comList.Concat(files).ToArray();

The ToArray() method is needed because Concat() returns an IEnumerable. Alternatively you can make comList an actual List<FileInfo> and use its AddRange method in each iteration:

comList.AddRange(files);

Upvotes: 1

Related Questions