문제

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