Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach loop fails to cast but manual casting and for loop work

This code doesn't work when it finds a none empty file throwing

Unable to cast object of type 'System.String' to type 'System.Web.HttpPostedFile'.

foreach (System.Web.HttpPostedFile f in Request.Files)
{
   if (f.ContentLength > 0 && f.FileName.EndsWith(".pdf"))
   {
      //work done here
   }
}

Also I tested each item in Request.Files array an can be manually casted in the debug mode as below (with each index)

?(System.Web.HttpPostedFile)Request.Files[index]
{System.Web.HttpPostedFile}
    ContentLength: 536073
    ContentType: "application/pdf"
    FileName: "E:\\2.pdf"
    InputStream: {System.Web.HttpInputStream}

However, Following code works

for (index = 0; index < Request.Files.Count; index++)
{
   System.Web.HttpPostedFile f = Request.Files[index];
   if (f.ContentLength > 0 && f.FileName.EndsWith(".pdf"))
   {
      //work done here
   }
}

Any idea what is going wrong? Thanks

like image 530
Kaf Avatar asked Feb 08 '13 13:02

Kaf


2 Answers

Request.Files is a HttpFileCollection, which is in turn a NameObjectCollectionBase. It isn't obvious, but the GetEnumerator() for that yields the keys for the collection - not the items themselves. So:

foreach(string key in Request.Files) {
    // fetch by key:
    var file = Request.Files[key];

    // ....
}

Not obvious, especially since the collection is non-generic IEnumerable rather than IEnumerable<string>.

It is at least documented:

This enumerator returns the keys of the collection as strings.

But: it was not unreasonable of you to suppose that iterating over the Files would give you the file objects.

like image 186
Marc Gravell Avatar answered Nov 02 '22 11:11

Marc Gravell


try like below.. it will work

foreach (string fName in Request.Files)
{
   System.Web.HttpPostedFile f = Request.Files[fName];
   if (f.ContentLength > 0 && f.FileName.EndsWith(".pdf"))
   {
      //work done here
   }
}

HttpFileCollection returns the keys of the files, not the HttpPostedFile objects.. so only it throws error..

like image 2
Pandian Avatar answered Nov 02 '22 11:11

Pandian