tags:

views:

325

answers:

2

Is there a way to create an instance of HttpPostedFile with Reflection.

I tried:

var obj = (HttpPostedFile)typeof(HttpPostedFile).GetConstructor(
                 BindingFlags.NonPublic | BindingFlags.Instance,
                 null, Type.EmptyTypes, null).Invoke(null);

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

But both of them do not work.

Update: apparently the internal constructor looks like this:

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

I tried this but without success:

Stream s = new MemoryStream(b.blob);
//var httpPostedFile = new HttpPostedFile();
Type[] parameters = { typeof(string), typeof(string), typeof(Stream) };

var obj = (HttpPostedFile)typeof(HttpPostedFile).GetConstructor(
      BindingFlags.NonPublic | BindingFlags.Instance,
      null, parameters, null)
      .Invoke(new object[] { "filename", "image/jpeg", s });
+1  A: 

HttpPostedFile class expects an instance of HttpInputStream class not a MemeoryStream. HttpInputStream again is an internal class so you need to create this using reflection. Do you really need to do this?

Shamika
+1  A: 

I'd go another route. Just add one more level of abstraction: create a IHttpPostedFile interface with all the members you need and use that both in your code and in tests. When you have this interface, you have two ways to go: you can either use duck typing to "cast" IHttpPostedFile to standard HttpPostedFile or you can implement this interface in your own class which will forward calls to an aggregated instance of HttpPostedFile class.

Anton Gogolev