开发者

Creating an instance of HttpPostedFile with Reflection

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.

Upda开发者_如何学Gote: 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 });


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.


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜