Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I cast from System.Web.HttpPostedFileBase to System.Web.HttpPostedFile?

While trying to implement an MVC file upload example on Scott Hanselman's blog. I ran into trouble with this example code:

foreach (string file in Request.Files)
{
   HttpPostedFile hpf = Request.Files[file] as HttpPostedFile;
   if (hpf.ContentLength == 0)
      continue;
   string savedFileName = Path.Combine(
      AppDomain.CurrentDomain.BaseDirectory, 
      Path.GetFileName(hpf.FileName));
   hpf.SaveAs(savedFileName);
}

I converted it to VB.NET:

For Each file As String In Request.Files
    Dim hpf As HttpPostedFile = TryCast(Request.Files(file), HttpPostedFile)
    If hpf.ContentLength = 0 Then
        Continue For
    End If
    Dim savedFileName As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.GetFileName(hpf.FileName))
    hpf.SaveAs(savedFileName)
Next

But I am getting an invalid cast exception from the compiler:

Value of type 'System.Web.HttpPostedFileBase' cannot be converted to 'System.Web.HttpPostedFile'.

Hanselman posted his example on 2008-06-27, and I assume it worked at the time. MSDN doesn't have any similar examples, so what gives?

like image 442
Jim Counts Avatar asked May 11 '09 17:05

Jim Counts


2 Answers

Just work with it as an HttpPostedFileBase. The framework uses the HttpPostedFileWrapper to convert an HttpPostedFile to an object of HttpPostedFileBase. HttpPostedFile is one of those sealed classes that are hard to unit test with. I suspect that sometime after the example was written they applied the wrapper code to improve the ability to test (using HttpPostedFileBase) controllers in the MVC framework. Similar things have been done with the HttpContext, HttpRequest, and HttpReponse properties on the controller.

like image 116
tvanfosson Avatar answered Sep 21 '22 09:09

tvanfosson


The correct type to use is HttpPostedFileBase.

HttpPostedFileBase hpf = Request.Files[file];
like image 31
Blake Pettersson Avatar answered Sep 23 '22 09:09

Blake Pettersson