How to Read the InfoPath content and extract the attachment using XMLDocument in C#

The InfoPath form:-

The namespace and the field1 that is node that contains the attachment

Sample Code:


XmlDocument myDoc = new XmlDocument();
myDoc.Load(@"C:\test\form.xml");

// specify the name space
XmlNamespaceManager ns = new XmlNamespaceManager(myDoc.NameTable);
ns.AddNamespace("my", "http://schemas.microsoft.com/office/infopath/2003/myXSD/2014-07-12T15:29:09");

// the node that contains the attachment
XmlNodeList nl = myDoc.SelectNodes("/my:myFields/my:group1/my:group2/my:field1", ns);
foreach (XmlNode n in nl)
{
string s = n.InnerText;
byte[] b = Convert.FromBase64String(s);
int nameBufferLen = b[20] * 2;

// file name buffer to get the filename with extension
byte[] fileNameBufffer = new Byte[nameBufferLen];

for (int i = 0; i < nameBufferLen; i++)
{
fileNameBufffer[i] = b[24 + i];
}
char[] charFileName = UnicodeEncoding.Unicode.GetChars(fileNameBufffer);
string fileName = new string(charFileName);
fileName = fileName.Substring(0, fileName.Length - 1);

// byte array for the remaining content
byte[] fileContent = new byte[b.Length - (24 + nameBufferLen)];

for (int i = 0; i < fileContent.Length; i++)
{
fileContent[i] = b[24 + nameBufferLen + i];
}

FileStream fs = new FileStream(@"C:\test\" + fileName, FileMode.Create);
fs.Write(fileContent, 0, fileContent.Length);
fs.Close();

}

Hope it helps..

 

 

 

 


Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

One thought on “How to Read the InfoPath content and extract the attachment using XMLDocument in C#”

Share your thoughts

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s