c# - 如何实例化 HttpPostedFile

标签 c# reflection file-upload

我正在尝试与我无法控制的系统进行通信,但是它的一种方法采用 HttpPostedFile 在我的代码中我有一个字节数组。有没有人有实例化 HttpPostedFile 的例子,因为我知道它的构造函数是内部的?

我找到的最好的是 Creating an instance of HttpPostedFile with Reflection它使用反射,但是它们被引导到另一个我不能接受的方向,因为我无法修改第三方系统方法签名。

最佳答案

这真的是非常 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, 0, data.Length});

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

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

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

  return postedFile;
}

关于c# - 如何实例化 HttpPostedFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5514715/

相关文章:

c# - C#中VB6中ObjPtr的等效(功能)?

c# - 如何为采用泛型参数的泛型函数调用 GetMethod(不使用 GetMethods)?

c# - Process.ProcessorAffinity 和 Thread.ProcessorAffinity 之间的区别

c# - 如何通过Azure功能上传大文件?

php - 在 Google App Engine (GAE) 中使用 zip_read 解压缩上传的文件

c# - 遍历通用对象属性

Scala:识别值类的对象

java - 如何将此 JScrollPane 类添加到我的 swing 构建器中?

java - 使用反射设置私有(private)静态最终字段

java - 我如何以编程方式将文件上传到网站?