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!

有帮助吗?

解决方案

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]))
{
    ...
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top