Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot implicitly convert type 'System.Web.HttpPostedFile' to 'System.Web.HttpPostedFileBase'

Tags:

asp.net

I have this method which does not build, it errors with the message:

Cannot implicitly convert type 'System.Web.HttpPostedFile' to 'System.Web.HttpPostedFileBase'

I really need this to be of type HttpPostedFileBase instead of HttpPostedFile, I have tried boxing and it does not work:

foreach (string inputTagName in HttpContext.Current.Request.Files)
{
    HttpPostedFileBase filebase =HttpContext.Current.Request.Files[inputTagName];
    if (filebase.ContentLength > 0)
    {
        if (filebase.ContentType.Contains("image/"))
        {
         SaveNonAutoExtractedThumbnails(doc, filebase);
        }
    }
}
like image 545
tom Avatar asked Jun 18 '10 17:06

tom


2 Answers

A quick peek at Reflector indicates that HttpPostedFileWrapper inherits from HttpPostedFileBase and accepts an HttpPostedFile in the constructor:

foreach (string inputTagName in HttpContext.Current.Request.Files)
{
    HttpPostedFileBase filebase = 
      new HttpPostedFileWrapper(HttpContext.Current.Request.Files[inputTagName]);

    if (filebase.ContentLength > 0)
    {
        //...

TheVillageIdiot brings up a great point about the better looping construct, and it will work for you if you're scope exposes the Request property of the current HTTP context (e.g. on a Page, but not in Global.asax):

foreach (HttpPostedFile file in Request.Files)
{
    HttpPostedFileBase filebase = new HttpPostedFileWrapper(file);
    // ..

If you have LINQ available, you could use that as well:

var files = Request.Files.Cast<HttpPostedFile>()
                .Select(file => new HttpPostedFileWrapper(file))
                .Where(file => file.ContentLength > 0 
                            && file.ContentType.StartsWith("image/"));

foreach (var file in files)
{
    SaveNonAutoExtractedThumbnails(doc, file);
}
like image 111
John Rasch Avatar answered Nov 14 '22 06:11

John Rasch


First thing you don't need to make it HttpPostedFileBase HttpPostedFile will work as fine.

Second, ContentType is MIME Content Type, you should look into FileName.

Try this code:

foreach (HttpPostedFile file in Request.Files)
{
    if (file.ContentLength > 0)
    {
        if(file.ContentType.Contains("image/") //as pointed out in comment
        {
            //make second parameter of type HttpPostedFile type
            //where you define method
            SaveNonAutoExtractedThumbnail(doc,file);
        }
    }
}
like image 3
TheVillageIdiot Avatar answered Nov 14 '22 07:11

TheVillageIdiot