Winsmarts.com

Microsoft MVP

MVP Logo

Awarded the Microsoft MVP Award.

Hosted By

blah!bLaH!BLOG!!

InfoPath 2007 - Extracting those pesky Binary attachments

Posted on 8/21/2008 @ 2:39 PM in #Sharepoint | 2 comments | 4624 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?

Easy.

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 -

   1:  
   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?


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 img.save...


thanks, atul

Please post your comments:


Your feedback will be submitted for moderation, and will appear after it is approved.

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 

Site designed and maintained by Sahil Malik | All Rights Reserved. ©2007 WinSmarts.com.