Search code examples
c#asp.netwebformshttppostedfilebase

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?


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.