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.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.
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..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With