Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get FileInfo via a foreach Loop?

Trying to convert some VB to C#... (learning C#, too). I have some code that loops through files in a directory and retrieves their file information. I have this originally in VB, but am trying to learn C#, and the online convertors don't give me code that will pass .net 2.0.

Here is the error: Type and identifier are both required in a foreach statement

Here is the code I have:

DirectoryInfo dirInfo = new DirectoryInfo(currentDir);
FileInfo[] files = null;
files = dirInfo.GetFiles();

FileInfo f = default(FileInfo);
foreach (f in files) {  ...
}

I tried putting foreach(FileInfo f... but it gives me a different error: A local variable named 'f' cannot be declared in this scope because it would give a different meaning to 'f', which is already used in a 'parent or current' scope to denote something else

How do I fix it?

like image 369
bgmCoder Avatar asked Dec 07 '22 14:12

bgmCoder


2 Answers

DirectoryInfo dirInfo = new DirectoryInfo(currentDir);
FileInfo[] files = null;
files = dirInfo.GetFiles();

// I removed the declaration of f here to prevent the name collision.
foreach (FileInfo f in files)
{  ...
}

Here is a simpler version of the code:

DirectoryInfo dirInfo = new DirectoryInfo(currentDir);
foreach (FileInfo f in dirInfo.GetFiles())
{
}
like image 179
Kendall Frey Avatar answered Dec 28 '22 00:12

Kendall Frey


Here's where it looks like you're going wrong:

FileInfo f = default(FileInfo);
foreach (f in files) {  ...
}

You are defining f outside of the loop, and then attempting to define it within the loop.

If you need the default to be f, try this:

FileInfo f = default(FileInfo);
foreach (FileInfo file in files)
    {
         relevant code here
    }

Otherwise delete the statement declaring the variable "f"

like image 45
Allison Steranko Avatar answered Dec 28 '22 01:12

Allison Steranko