Creating WPF BitmapImage from MemoryStream png, gif

Add bi.CacheOption = BitmapCacheOption.OnLoad directly after your .BeginInit(): BitmapImage bi = new BitmapImage(); bi.BeginInit(); bi.CacheOption = BitmapCacheOption.OnLoad; … Without this, BitmapImage uses lazy initialization by default and stream will be closed by then. In first example you try to read image from possibly garbage-collected closed or even disposed MemoryStream. Second example uses file, which is … Read more

Attach a file from MemoryStream to a MailMessage in C#

Here is the sample code. 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(); ms.Position = 0; 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”; // I guess you know how to send email with an attachment // after sending email … Read more