0

I want to loop through files and always make sure its just one item in the array I am looping through

var files = Request.Form.Files;
var singleFile = files[0];
foreach (var file in singleFile)
{

}

I am getting the error foreach statement cannot operate on variables of type '?' because '?' does not contain a public definition for 'GetEnumerator'

How can I fix this ! Thanks

4
  • 6
    Why do you want to iterate single item? singleFile already contains first item of the array. Commented Jan 17, 2018 at 12:17
  • 1
    Can you explain what you mean by "looping through"? How can you loop through a single item? Commented Jan 17, 2018 at 12:17
  • I just want to make sure that it is always getting the first item in the loop as people may upload 2 files at the same time if that makes sense Commented Jan 17, 2018 at 12:19
  • 1
    files[0] will always get the first item in the collection. If that's all you want you're done. You can't iterate that item because it is an item, not a collection. Commented Jan 17, 2018 at 12:21

3 Answers 3

3

You can't loop through an item that is not a collection type. You have assigned the first file in Request.Form.Files to a variable. So this variable references a single file not all.

You can use the Count-property of the HttpFileCollection:

int fileCount = Request.Form.Files.Count;
if(fileCount > 0)
{
    HttpPostedFile firstFile = Request.Form.Files[0];
    // do something with it ....
}

If you want to enumerate all you can use a loop but on Request.Form.Files:

foreach (HttpPostedFile file in Request.Form.Files)
{
    // do something with it
}
Sign up to request clarification or add additional context in comments.

Comments

2

The error is pretty clear. singleItem is just one single item from your original collection, not the actual collection. If you want to check, that the collection has only one element, use files.Count:

if(files.Count != 1)
    Console.WriteLine("Evil, evil");
else
{
    var singleFile = files[0];
    // ....
}

Comments

0

try this, it will give the first item of collection. if the collection count is 0, then it will return null.

Request.Form.Files.FirstOrDefault()

1 Comment

Since Request.Form.Files is not an array but a HttpFileCollection which doesn't implement IEnumerable<T> this won't compile

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.