none
How to send attachment from MemoryStream image RRS feed

  • Question

  • Hi,

    I am trying to get the image from sql server and save it into memory stream ten put it as an  attachment instead of saving the file as physical file on the PC.

    I am trying below code but not working and keeps throwing error whatever I tried.

    Kindly help...

    if (sql_reader_attachment["customer_image"] != DBNull.Value)
    {
        byte[] rawData = (byte[])sql_reader_attachment["customer_image"];
    
        using (image_memory_stream = new MemoryStream(rawData))
        {
    Image.FromStream(image_memory_stream).Save(image_memory_stream, System.Drawing.Imaging.ImageFormat.Png);
    
            image_memory_stream.Seek(0, System.IO.SeekOrigin.Begin);
    
            Attachment customer_image = new Attachment(image_memory_stream, "Image-" + sql_reader_attachment["customer_image_id"].ToString() + ".png", "image/png");
            mail_message.Attachments.Add(customer_image);
        }
    }
    

    Thanks,

    Jassim

    Friday, June 17, 2016 8:09 PM

Answers

  • What error?

    What is "Attachment"?

    Image.FromStream(S).Save(S) is wrong.  You should use separate MemoryStreams, as re-encoding the image will change its length, and your MemoryStream is opened over an existing byte[].

    David


    David http://blogs.msdn.com/b/dbrowne/

    • Marked as answer by Jassim Rahma Friday, June 17, 2016 8:20 PM
    Friday, June 17, 2016 8:12 PM

All replies

  • What error?

    What is "Attachment"?

    Image.FromStream(S).Save(S) is wrong.  You should use separate MemoryStreams, as re-encoding the image will change its length, and your MemoryStream is opened over an existing byte[].

    David


    David http://blogs.msdn.com/b/dbrowne/

    • Marked as answer by Jassim Rahma Friday, June 17, 2016 8:20 PM
    Friday, June 17, 2016 8:12 PM
  • sorry this is the complete code, and attachment is System.Net.Mail.Attachment

    while (sql_reader_attachment.Read())
    {
        if (sql_reader_attachment["customer_image"] != DBNull.Value)
        {
            byte[] rawData = (byte[])sql_reader_attachment["customer_image"];
    
            using (image_memory_stream = new MemoryStream(rawData))
            {
                attachment_memory_stream = new MemoryStream();
    
                Image.FromStream(image_memory_stream).Save(attachment_memory_stream, System.Drawing.Imaging.ImageFormat.Png);
    
                attachment_memory_stream.Seek(0, System.IO.SeekOrigin.Begin);
    
                Attachment customer_image = new Attachment(attachment_memory_stream, "Image-" + sql_reader_attachment["customer_image_id"].ToString() + ".png", "image/png");
                mail_message.Attachments.Add(customer_image);
            }
        }
    }
    

    Friday, June 17, 2016 8:17 PM
  • My problem solved by saving to another memory stream.

    Thanks Daid

    Friday, June 17, 2016 8:20 PM