How to add item in array through a foreach?

Asked

Viewed 2,511 times

3

I’m doing a check in a directory where I list all items with a specific extension.

And I need to add the items into one array through a foreach.

Follow 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 overrides taking only the last value of the array in rgFiles[].

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

  • 2

    FileInfo[] rgFiles = di.GetFiles("*.ost"); here it already brings you an array of information, can not use this?

  • 1

    The mistake is here: pasta = new string[] { item.FullName };. You create a new instance by overriding the previous one. Do with foreach It does, but it’s not the right thing for what you need, it would be too much unnecessary code. I recommend evaluating @Virgilionovic’s comment and response

2 answers

4

Can use Linq, not specified in this specific case to use a repeating structure.

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

1


I believe the problem is attribution. It needs to be array really? I think it would be better to do with a 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;

I put in the Github for future reference.

  • on line 3 in the example code, it gives me an error in [rgFiles.Length]. In the error it says: A Constant value is expected.

  • 1

    @Renancarlos There was a problem even, I forgot to take the keys. I edited now tries. See that boot works with variable size: https://dotnetfiddle.net/TszpBD. Note that the array cannot grow. If you need this then it would be better to use a list.

  • worked perfectly. And exactly as I wanted. Thanks !!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.