在 .NET 4.5 beta 中将 System.Net.Mail.MailMessage 作为 MemoryStream [英] Getting System.Net.Mail.MailMessage as a MemoryStream in .NET 4.5 beta
问题描述
因此,以下代码用于在 .NET 4 中获取 System.Net.Mail.MailMessage 对象作为 MemoryStream,但是随着 .NET 4.5 beta 的发布,出现运行时异常.
So, the below code used to work in .NET 4 to get a System.Net.Mail.MailMessage object as a MemoryStream, however with the release of .NET 4.5 beta a runtime exception occurs.
Assembly assembly = typeof(SmtpClient).Assembly;
Type mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");
using (MemoryStream stream = new MemoryStream())
{
ConstructorInfo mailWriterContructor = mailWriterType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(Stream) }, null);
object mailWriter = mailWriterContructor.Invoke(new object[] { stream });
MethodInfo sendMethod = typeof(MailMessage).GetMethod("Send", BindingFlags.Instance | BindingFlags.NonPublic);
sendMethod.Invoke(message, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { mailWriter, true }, null);
.....
}
在 sendMethod.Invoke() 上发生运行时异常.
Runtime exception occurs on sendMethod.Invoke().
推荐答案
设法找出如何在 .NET 4.5 测试版中再次运行此功能.MailMessage 中的私有 API Send() 方法更改为:internal void Send(BaseWriter writer, bool sendEnvelope, bool allowUnicode)
Managed to figure out how to get this working again in .NET 4.5 beta. The private API Send() method in MailMessage has changed to: internal void Send(BaseWriter writer, bool sendEnvelope, bool allowUnicode)
请在下面找到更新的代码.
Please find updated code below.
Assembly assembly = typeof(SmtpClient).Assembly;
Type mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");
using (MemoryStream stream = new MemoryStream())
{
ConstructorInfo mailWriterContructor = mailWriterType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(Stream) }, null);
object mailWriter = mailWriterContructor.Invoke(new object[] { stream });
MethodInfo sendMethod = typeof(MailMessage).GetMethod("Send", BindingFlags.Instance | BindingFlags.NonPublic);
sendMethod.Invoke(message, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { mailWriter, true, true }, null);
.....
}
这篇关于在 .NET 4.5 beta 中将 System.Net.Mail.MailMessage 作为 MemoryStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!