简体   繁体   English

MemoryStream不会填充附件

[英]MemoryStream doesn't fill attachment

I am developing a method for C# where to send as an attachment a byte[]. 我正在为C#开发一个方法,在那里作为附件发送一个byte []。 The method below sends fine the email, but the attachment is always empty. 下面的方法可以发送电子邮件,但附件始终为空。

 public bool envio(MailMessage mail, SmtpClient cliente, byte[] origen)
        {
            bool res = true;
            System.IO.MemoryStream ms;
            System.IO.StreamWriter writer;

            ms = new System.IO.MemoryStream();
            writer = new System.IO.StreamWriter(ms);

            try
            {    
                writer.Write(origen);
                writer.Flush();                

                System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Plain);
                System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, ct);
                attach.Name = "Mensaje";
                mail.Attachments.Add(attach);

                cliente.Send(mail);

            }

            catch (Exception ex)
            {

                res = false;
            }

            finally

            {
                writer.Close();
                writer.Dispose();                
                ms.Close();
                ms.Dispose();
            }
            return res;

        }

I am pretty sure it should be something obvious for an expert developer. 我很确定它对于专业开发人员应该是显而易见的。 but I can't find out the solution. 但我找不到解决方案。

Thx in advance. Thx提前。

When you finish writing to the stream, it's position is at the end of the data. 写完流后,它的位置就在数据的末尾。 So when someone tries to read from the stream, there's nothing left to read. 因此,当有人试图从流中读取时,没有什么可读的。 The solution is simple: 解决方案很简单:

writer.Write(origen);
writer.Flush();
ms.Position = 0;

Also, since you're dealing with plain text here, be careful about encoding. 此外,由于您在此处理纯文本,因此请注意编码。 Use explicit encodings where possible to minimize encoding issues :) 尽可能使用显式编码来最小化编码问题:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM