I'm trying to communicate with a system which I have no control over, however one of its methods takes in a HttpPostedFile were in my code I have a byte array. Does anybody have an example of instantiating a HttpPostedFile as I know its constructor is internal?
The best I've found is Creating an instance of HttpPostedFile with Reflection which uses reflection, however they were steered into another direction which I can't take because I am unable to modify the third party systems method signature.
This is really really hacky code, but the following seems to work for me:
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;
}
you can try
var constructorInfo = typeof(HttpPostedFile).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)[0];
var obj = (HttpPostedFile)constructorInfo
.Invoke(new object[] { "filename", "image/jpeg", null });
obj
would of type HttpPostedFile
.I'm setting the last parameter to null but it has to be a HttpInputStream though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With