InfoPath 2007 - Extracting those pesky Binary attachments

Posted on 8/21/2008 @ 2:39 PM in #SharePoint by | Feedback | 9430 views

In InfoPath 2007, including browser enabled forms, you have the ability to use a control called "File Attachment". When rendered in the browser, it looks like this -



What it has done is, it has embedded a bunch of information, as a byte stream, right inside the XML. Specifically, the filename, and filebytes are embedded.

How can you extract that attachment, in code?


Step #1 - create a strongly typed representation of your form, as I illustrated in this blogpost.

Step #2 -

Now assuming that your field name was "fldImage", and assuming that the file uploaded was an Image, you can use the following code to extract the filename, and the file itself -

   2:  byte[] imageBytes = fields.fldImage;
   3:  MemoryStream ms = new MemoryStream(imageBytes);
   4:  BinaryReader theReader = new BinaryReader(ms);
   5:  theReader.ReadBytes(16); // Skip the header data.
   6:  int fileSize = (int)theReader.ReadUInt32();
   7:  int attachmentNameLength = (int)theReader.ReadUInt32() * 2;
   8:  byte[] fileNameBytes = theReader.ReadBytes(attachmentNameLength);
   9:  Encoding enc = Encoding.Unicode;
  10:  string attachmentName = enc.GetString(fileNameBytes, 0, attachmentNameLength - 2);
  11:  byte[] decodedAttachment = theReader.ReadBytes(fileSize);
  12:  Image img = Image.FromStream(new MemoryStream(decodedAttachment));
  13:  img.Save("testimage.jpg", ImageFormat.Jpeg);


Easy huh?

Sound off but keep it civil:

Older comments..

On 9/8/2008 1:43:33 PM Verzekering said ..
It worked here, but I hadn't found it, without your code..

On 10/31/2008 11:30:28 AM Atul Chhoda said ..
Very useful !

For storing attachments of other types , pdf, docs,....

use File.WriteAllBytes(attachmentName , decodedAttachment);

instead of

thanks, atul

On 6/17/2010 6:45:33 PM Brad said ..
This code works great for InfoPath 2007, but I am presented with an "index out of range" error when upgrading to InfoPath 2010. This error occurs when extracting the attachment name from the image. Any idea what would be causing this?

On 8/20/2012 7:15:06 PM Kevin said ..
Hi I am new to Infopath 2007. Can you help provide step-by-step instructions? I am confused where I should add the code you provided...


On 2/5/2013 4:20:44 PM MS said ..
Thanks, This works great!