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
Request.Filesis aHttpFileCollection, which is in turn aNameObjectCollectionBase. It isn’t obvious, but theGetEnumerator()for that yields the keys for the collection – not the items themselves. So:Not obvious, especially since the collection is non-generic
IEnumerablerather thanIEnumerable<string>.It is at least documented:
But: it was not unreasonable of you to suppose that iterating over the
Fileswould give you the file objects.