How to add item in array through a foreach?

2

I'm doing a check in a directory where all the items with a specific extension are ready.

I need to add the items in an array via a foreach .

Here's part of the code I've tried.

 DirectoryInfo di = new DirectoryInfo(_caminhoEmail);
 FileInfo[] rgFiles = di.GetFiles("*.ost");
 string[] pasta = new string[] { };
 foreach (FileInfo item in rgFiles)
 {
     pasta = new string[] { item.FullName};
 }
 return pasta;

But with this code it always overwrites taking only the last array value in rgFiles[] .

How do I add items in Array pasta and return it at the end?

    
asked by anonymous 11.10.2016 / 15:35

2 answers

1

I believe the problem is attribution. need to be array anyway? I think it would be best to do with for .

 var di = new DirectoryInfo(_caminhoEmail);
 FileInfo[] rgFiles = di.GetFiles("*.ost");
 var pasta = new string[regFiles.Length];
 for (var i = 0; i < rgFiles.Length; i++) {
     pasta[i] = rgFiles[i].FullName;
 }
 return pasta;
    
11.10.2016 / 15:42
4

You can use Linq , so you do not need to use a repetition structure in this case.

DirectoryInfo di = new DirectoryInfo(_caminhoEmail);
FileInfo[] rgFiles = di.GetFiles("*.ost");
return rgFiles.Select(e => e.FullName).ToList();
    
11.10.2016 / 15:39