Click to See Complete Forum and Search --> : Populating listbox with file names


silentB4thedawn
June 6th, 2009, 11:01 PM
Here's the code that I'm currently using in VS C# 2010:
// update listbox
DirectoryInfo dir = new DirectoryInfo((Application.StartupPath + "\\CustomerCollectionData\\"));
// create array containing filenames
FileInfo[] file = dir.GetFiles();
// print out the file names
FileInfo fiTemp;
foreach (fiTemp in file)
{
listBox1.Items.Add(fiTemp.Name);
}

I get an error under the "foreach (fiTemp in file)" line; specifically red-underlined "fiTemp" & "in" saying:

"Type or namespace name 'fiTemp' could not be found"
(under "fiTemp")

and
"Type and identifier are both required in a foreach statement"
(under "in")

According to my research on this topic, the syntax should be right, unless I missed something...
Anyone know what the issue is?

sotoasty
June 7th, 2009, 08:23 AM
I am not completely sure, but from the error messages it sounds like you need to change the code to this.


foreach (FileInfo fiTemp in file)
{
listBox1.Items.Add(fiTemp.Name);
}


The error message "Type and identifier are both required in a foreach statement" means that you need to declare what type of object you are looking for in "file". Don't declare the object beforehand, it must be declared in the foreach.

silentB4thedawn
June 7th, 2009, 02:03 PM
Well, you were partly right. I can't believe I didn't catch it before.
This:


FileInfo fiTemp;


I was declaring it there... Then here:


foreach (FileInfo fiTemp in file)


I was basically redeclaring it...

Thanks so much