I'm trying to send email with attachment using C#. Here is my method:
public void SendEmail(string from, string to, SmtpClient client)
{
MailMessage mm = new MailMessage(from, to, "Otrzymałeś nowe zamówienie od "+from , "Przesyłam nowe zamówienie na sprzęt");
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
// Adding attachment:
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.StreamWriter writer = new System.IO.StreamWriter(ms);
writer.Write("Hello its my sample file");
writer.Flush();
writer.Dispose();
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.ContentDisposition.FileName = "myFile.txt";
mm.Attachments.Add(attach);
try
{
client.Send(mm);
}
catch(SmtpException e)
{
Console.WriteLine(e.ToString());
}
ms.Close();
}
stacktrace points to this line:
client.Send(mm);
problem is caused by this line:
writer.Dispose();
Why I can not dispose this element right after using it to write into MemoryStream
?
This element isn't used any time later in the code.
Calling Dispose on the writer also Disposes the underlying stream. You have to dispose both the writer and the stream after the email has been sent. You can achieve that by wrapping your code in two using statements.
using(var ms = new System.IO.MemoryStream())
{
using(var writer = new System.IO.StreamWriter(ms))
{
writer.Write("Hello its my sample file");
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.ContentDisposition.FileName = "myFile.txt";
mm.Attachments.Add(attach);
try
{
client.Send(mm);
}
catch(SmtpException e)
{
Console.WriteLine(e.ToString());
}
}
}