Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why am I getting HttpPostedFile instead of HttpPostedFileBase when iterating HttpFileCollection?

I’m iterating over an HttpFileCollection and trying to get a List<HttpPostedFileBase> as the result.

public List<HttpPostedFileBase> GetFiles()
{
    HttpFileCollection files = HttpContext.Current.Request.Files;
       
    List<HttpPostedFileBase> result = new List<HttpPostedFileBase>();

    foreach (string fileName in files)
    {
        HttpPostedFileBase castedFile = files[fileName]; //This is HttpPostedFile and not HttpPostedFileBase
        result.Add(castedFile);
    }

    return result;
}

How can I get a List<HttpPostedFileBase> out of an HttpFileCollection?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

HttpPostedFile does not derive from HttpPostedFileBase. If you really want to return List<HttpPostedFileBase> instead of List<HttpPostedFile>, then wrap each HttpPostedFile object within an HttpPostedFileWrapper object:

HttpPostedFileBase castedFile = new HttpPostedFileWrapper(files[fileName]);

As the HttpPostedFileWrapper documentation says:

The HttpPostedFileWrapper class derives from the HttpPostedFileBase class and serves as a wrapper for the HttpPostedFile class. This class exposes the functionality of the HttpPostedFile class while also exposing the HttpPostedFileBase type.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading