加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何实例化一个HttpPostedFile

发布时间:2020-12-15 06:41:26 所属栏目:百科 来源:网络整理
导读:我正在尝试与一个我无法控制的系统进行通信,但是其中一个方法需要一个HttpPostedFile在我的代码中,我有一个字节数组.有谁有一个例子来实例化一个HttpPostedFile,因为我知道它的构造函数是内部的? 我发现最好的是this SO post,它使用反射,但是他们被引导到另
我正在尝试与一个我无法控制的系统进行通信,但是其中一个方法需要一个HttpPostedFile在我的代码中,我有一个字节数组.有谁有一个例子来实例化一个HttpPostedFile,因为我知道它的构造函数是内部的?

我发现最好的是this SO post,它使用反射,但是他们被引导到另一个方向,我不能采取,因为我无法修改第三方系统方法签名.

解决方法

这真的是真的hacky代码,但以下似乎适用于我:
public HttpPostedFile ConstructHttpPostedFile(byte[] data,string filename,string contentType) {
  // Get the System.Web assembly reference
  Assembly systemWebAssembly = typeof (HttpPostedFileBase).Assembly;
  // Get the types of the two internal types we need
  Type typeHttpRawUploadedContent = systemWebAssembly.GetType("System.Web.HttpRawUploadedContent");
  Type typeHttpInputStream = systemWebAssembly.GetType("System.Web.HttpInputStream");

  // Prepare the signatures of the constructors we want.
  Type[] uploadedParams = { typeof(int),typeof(int) };
  Type[] streamParams = {typeHttpRawUploadedContent,typeof (int),typeof (int)};
  Type[] parameters = { typeof(string),typeof(string),typeHttpInputStream };

  // Create an HttpRawUploadedContent instance
  object uploadedContent = typeHttpRawUploadedContent
    .GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance,null,uploadedParams,null)
    .Invoke(new object[]{data.Length,data.Length});

  // Call the AddBytes method
  typeHttpRawUploadedContent
    .GetMethod("AddBytes",BindingFlags.NonPublic | BindingFlags.Instance)
    .Invoke(uploadedContent,new object[] {data,data.Length});

  // This is necessary if you will be using the returned content (ie to Save)
  typeHttpRawUploadedContent
    .GetMethod("DoneAddingBytes",null);

  // Create an HttpInputStream instance
  object stream = (Stream)typeHttpInputStream
    .GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance,streamParams,null)
    .Invoke(new object[] {uploadedContent,data.Length});

  // Create an HttpPostedFile instance
  HttpPostedFile postedFile = (HttpPostedFile)typeof(HttpPostedFile)
    .GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance,parameters,null)
    .Invoke(new object[] {filename,contentType,stream});

  return postedFile;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读