c# - Cannot access a closed stream while sending attachment -


i'm trying send email attachment using c#. here 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 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 line:

client.send(mm); 

problem caused line:

writer.dispose(); 

why can not dispose element right after using write memorystream? element isn't used time later in code.

calling dispose on writer disposes underlying stream. have dispose both writer , stream after email has been sent. can achieve wrapping code in 2 using statements.

    using(var ms = new system.io.memorystream())     {       using(var writer = new system.io.streamwriter(ms))       {          writer.write("hello 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());          }        }     } 

Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -