views:

118

answers:

3

I'm trying to create an instance of HttpPostedFile with

var obj2 = Activator.CreateInstance(
    typeof(HttpPostedFile), 
    BindingFlags.NonPublic | BindingFlags.Instance,
    null,
    new object[] { },
    System.Globalization.CultureInfo.CurrentCulture
);

but I'm getting the error 'Constructor on type 'System.Web.HttpPostedFile' not found.'.

Is there another way to create an instance of HttpPostedFile or am I doing something wrong?

+1  A: 

HttpPostedFile has an internal constructor that takes 3 arguments and that is not intended to be called from your code:

internal HttpPostedFile(string filename, string contentType, HttpInputStream stream)

In order to instantiate this class you will need to pass a filename, a content type and a HttpInputStream instance which is a type that is also internal so the only way to instantiate it is through reflection.

Darin Dimitrov
And how would you instantiate it with reflection because I can't seem to figure it out.
Lieven Cardoen
A: 

HttpPostedFile does not expose public constructors, it's available with the file upload control.

I think you should use some other class, so what exactly are you trying to do with the HttpPostedFile?

Skrim
I need an instance of it for a unit test I'm writing.
Lieven Cardoen
+2  A: 

You might be able to use System.Web.HttpPostedFileBase instead. This has the same methods as HttpPostedFile but is designed for sub-classing. You can then use HttpPostedFileWrapper to pass in a real HttpPostedFile to a method expecting an HttpPostedFileBase.

These extra classes are in the System.Web.Abstractions assembly. ASP.NET MVC makes use of this (and other abstractions in the same assembly) to make unit testing easier. See the documentation on MSDN for more information.

Ben Lings