The request was aborted: The connection was closed unexpectedly

I got a exception while sending a mail that The request was aborted: The connection was closed unexpectedly.  I don’t know why it is happening.. After some researching i got a point that this is because i am disposing  http response object before reading from its stream.

Code i got exception
using(Stream stream = req.GetResponse().GetResponseStream()){
if (stream != null)
{
attachment = new Attachment(stream, ct);
message.Attachments.Add(attachment);
}
}

Send mail after disposing the stream object
client.Send(message);

Solution

Don’t try to pass the stream object after disposing. The using statement obtains the resource specified, executes the statements and finally calls the Dispose method of the object to clean up the object.
Corrected Code

using(Stream stream = req.GetResponse().GetResponseStream()){
if (stream != null)
{
attachment = new Attachment(stream, ct);
message.Attachments.Add(attachment);
client.Send(message);
}
}

Enjoy coding…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s