创建EML文件MethodInfo.Invoke,给出参数计数不匹配

时间:2013-11-22 01:22:32

标签: c#

我正在尝试创建.eml文件。我使用下面的代码。但无论何时它到达method.Invoke它给我错误参数计数不匹配。 .Below是我创建eml文件的代码。

    try
        {
           MailMessage m = new MailMessage();
           m.Body = htmlbody;
           var htmlView = AlternateView.CreateAlternateViewFromString(m.Body, null, "text/html");

            MailAddress newFromAddress = new MailAddress("select.sender@sender.com", "(Please select sender)");
            m.Sender = null;
            m.From = newFromAddress;
            m.Headers.Add("X-Unsent", "1");  //Make the eml file open in compose mode
            m.AlternateViews.Add(htmlView);  //Add the html content to the email
            m.Subject = subject;
            m.IsBodyHtml = true;

            var assembly = typeof(SmtpClient).Assembly;
            var mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");
            using (MemoryStream stream = new MemoryStream())
            {
                //Construct the mail message file .eml
                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);
                ///**This is line where I get error**///  sendMethod.Invoke(m, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { mailWriter, true, true }, null);  

                return stream.ToArray();
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.ToString());
        }

更新: 我正在使用.Net Framework 2.0。这是问题吗?

1 个答案:

答案 0 :(得分:2)

查看源代码,看起来Send方法只需要2个参数

 internal void Send(BaseWriter writer, bool sendEnvelope)

http://www.dotnetframework.org/default.aspx/DotNET/DotNET/8@0/untmp/whidbey/REDBITS/ndp/fx/src/Net/System/Net/Mail/MailMessage@cs/2/MailMessage@cs

您需要将这些传递给调用调用。

sendMethod.Invoke(m, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { mailWriter, true}, null);