Question

I was working on my website when i noticed my foreach loop wasn't working to upload a list of files and a for loop did work. I am curious to find out why the for loop works and the foreaches loop aren't.

The error message i got was: Cannot cast system.string to xx.

So these are the loops i have:

HttpFileCollection documentsList = Request.Files;

// Doesn't
foreach (var file in documentsList.Cast<HttpPostedFile>())
{
    var test = file;
}

// Doesn't
foreach (var file in documentsList)
{
    var test = (HttpPostedFile)file;
}

// Works
for (int i = 0; i < documentsList.Count; i++)
{
    var file = (HttpPostedFile) documentsList[i];
}

Thanks in advance!

Was it helpful?

Solution

As soon as you look at HttpFileCollection's documentation, it becomes clearer...

The indexer has a declared type of HttpPostedFile. Whereas GetEnumerator states:

This enumerator returns the keys of the collection as strings.

So basically your foreach loop is iterating over the keys in the collection, whereas you want the values. This is inherently a weird design decision in NameObjectCollectionBase.

You could use:

foreach (var file in documentsList.Cast<string>()
                                  .Select(key => documentsList[key]))
{
    ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top