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?
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.
The correct type to use is HttpPostedFileBase.
HttpPostedFileBase hpf = Request.Files[file];
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