The exception in my questions title is being thrown on the line return allMessages; in the code below. I don't understand it because that line of code is still within the using (var sslStream...) statement, so by the time it is executed the SslStream object should not be disposed..
public static List<Message> FetchAllMessages(string hostname, int port, string username, string password, string proxyIp, int proxyPort)
{
// The client disconnects from the server when being disposed
using (Pop3Client client = new Pop3Client())
{
var proxyClient = new HttpProxyClient(proxyIp, proxyPort);
using (var sslStream = new SslStream(proxyClient.CreateConnection(hostname, port).GetStream()))
{
sslStream.AuthenticateAsClient(hostname);
client.Connect(sslStream);
// Authenticate ourselves towards the server
client.Authenticate(username, password);
// Get the number of messages in the inbox
int messageCount = client.GetMessageCount();
// We want to download all messages
List<Message> allMessages = new List<Message>(messageCount);
// Messages are numbered in the interval: [1, messageCount]
// Ergo: message numbers are 1-based.
// Most servers give the latest message the highest number
for (int i = messageCount; i > 0; i--)
{
allMessages.Add(client.GetMessage(i));
}
// Now return the fetched messages
return allMessages;
}
}
}
UPDATES:
Put a breakpoint on return allMessages; and hovered over the sslStream object, it is not disposed.
When I remove the using statement and just declare var sslStream it works but I don't think this would scale well without it..
client.GetMessage(i). Try to clone it. Well, right. client holds to the message, you add message to list. This is same instance. When you dispose client, it disposes message. Try doingToMailMessageand add to list. This should workbytes = client.GetMessageAsBytes();thenlist.Add(new Message(bytes));. Should do it. This is your clone mechanism. If this works, I'll post pretty solution answer. Let me knowSslStreamandpo3Clientand look into itsDispose