Appvity Blog

Home of the SharePoint mobility topics

How to Programmatically Create an InfoPath Form from an InfoPath XSN Template

By Phong Dang posted June 24, 2013 05:26 | 43 Comments

By Phong Dang posted June 24, 2013 05:26 | 43 Comments

Let's say you design an InfoPath form and upload the associated form template into the SharePoint Central Administration site. What would you do if you wanted to create a new item in the Form Library based on this template?

For example, I have a Form Library with the Project Information form and InfoPath template (Project Information.xsn) uploaded in the Central Administration site. These features are activated on the SharePoint site. I will create a new program that shows how to programmatically create an InfoPath form from an InfoPath XSN template.

First, I create a new solution and name it Appvity.InfoPathFormSoln

Next, I add two reference assemblies: Microsoft.Office.InfoPath.dll and Microsoft.Office.InfoPath.Server.dll, in order to use the InfoPath API.


Next, I add a new feature, Appvity.InfoPath, and set up the required information.

Note: I do not want to activate this feature automatically so I set the Active On Default option to false.

Next, I add a new event receiver for this feature. I do want to activate this feature, as my form library will update the InfoPath form and content type.

Before implementing code for this event receiver, I create a new page, FormXmlParser.aspx. This page will help me read the Project Information.xsn template and generate it to template.xml.

Note: Project Informaion.xsn is a cab file so you must extract the content before you can modify it. There are many methods to extract this file (such as:, but those methods do not work in SharePoint. Thus, I create an ASP.Net page. On this page, there is an instance of an XmlFormView control. An XmlFormView is an InfoPath Forms Services control that hosts an InfoPath form on any ASP.Net page (as long as you're running it in SharePoint). You can also host the XSN template, which is what this code will do.

Note: Note the use of the OpenFileFromPackage method in the Initialize event handler. That is a method that will extract the template.xml file (or any other file) from the XSN. The template.xml file is a "blank" form used to create a new instance of an InfoPath form from a template.

Next, to make sure this page works correctly, you want to deploy this project to a SharePoint server and browse this page:

Back to event receiver class, I implement the FeatureActivated event.

Now, you need to activate the Project Information content type in the form library and get the absolute path of the InfoPath template from the root web and then point it to your custom web page in the code and download the xml. After that, do whatever you want with the xml, and place it in a form library.

public override void FeatureActivated(SPFeatureReceiverProperties properties)
                string listName = "ProjectInformation";
                string strContentType = "Project Information";
                SPWeb web = properties.Feature.Parent as SPWeb;
                SPList formLibrary = null;

                    formLibrary = web.GetList(web.Url + "/" + listName);

                if (formLibrary != null)
                    SPContentType contentType = web.AvailableContentTypes.OfType<SPContentType>().Where(ct => ct.Name.Equals(strContentType)).FirstOrDefault();

                    if (contentType != null)
                        SPContentType infoPath = formLibrary.ContentTypes.OfType<SPContentType>().Where(c => c.Name.Equals(contentType.Name)).FirstOrDefault();

                        if (infoPath == null)
                            contentType = formLibrary.ContentTypes.Add(contentType);
                            SPFolder rootFolder = formLibrary.RootFolder;

                            //Add the content type back
                            IList<SPContentType> ctList = rootFolder.ContentTypeOrder;
                            rootFolder.UniqueContentTypeOrder = ctList;
                            contentType = infoPath;
                    string templateUrl = contentType.DocumentTemplateUrl;
                    SPFolder forms = web.GetFolder(web.Url + "/" + listName);

                    if (forms != null)
                        WebClient client = new WebClient();
                        client.Credentials = CredentialCache.DefaultCredentials;

                        if (templateUrl.LastIndexOf("/") != -1)
                            templateUrl = templateUrl.Substring(templateUrl.LastIndexOf("/"));
                            templateUrl = "/FormServerTemplates" + templateUrl;

                        string fileInfoPath = web.Site.Url + templateUrl;
                        Stream stream = client.OpenRead(web.Url + "/_layouts/Appvity.InfoPathForm/FormXmlParser.aspx?Url=" + fileInfoPath);
                        StreamReader reader = new StreamReader(stream);
                        string formXml = reader.ReadToEnd();
                            XmlDocument xmlDoc = new XmlDocument();
                            Stream outStream = new MemoryStream();
                            SPFile file = forms.Files.Add(formLibrary.Title + ".xml", outStream, true);
                            SPListItem item = formLibrary.Items[file.UniqueId];
                            item["TemplateUrl"] = fileInfoPath;

Everything is ready. Let’s deploy the solution in our site and enjoy the results. 




Downloading the file demo : Appvity.InfoPathFormSoln.rar (91.82 kb).

Comments (43) -

thanks a lot for this tutorial. Can you re-upload the solution.
Thanks in advance

With havin so much written content do you ever run into any issues of plagorism or copyright violation? My website has a lot of unique content I've either created myself or outsourced but it seems a lot of it is popping it up all over the web without my agreement. Do you know any methods to help protect against content from being stolen? I'd definitely appreciate it.

What a totally amazing website. You've got something special going on here!

Downloading the demo code is inaccessible.
Can you please share the code?

Also, please explain what is UpdateInfoPathForm...

I could not find any thing about that...

I added a new list. As you'll see it's bigger than most of them. I hope you all have had a great week!

I’ve been having issues with my Windows hosting. It has set me back quite a bit while making the next list. This is the current list that I have. I should add another list in less than a week. I’ll let you all know when the next list is ready. Thank you for your patience.

We are a bunch of volunteers and starting a brand new scheme in our community. Your web site provided us with useful information to work on. You have done an impressive task and our entire community might be grateful to you.

Hello! I know this is kinda off topic but I was wondering if you knew where I could locate a captcha plugin for my comment form? I'm using the same blog platform as yours and I'm having problems finding one? Thanks a lot!

Hey just wanted to give you a quick heads up and let you know a few of the images aren't loading properly. I'm not sure why but I think its a linking issue. I've tried it in two different browsers and both show the same results.

You have made some really good points there. I checked on the web to find out more about the issue and found most people will go along with your views on this website.

You actually make it seem really easy along with your presentation but I in finding this matter to be actually one thing which I feel I'd by no means understand. It seems too complex and very extensive for me. I am looking forward to your next post, I will attempt to get the dangle of it!

You get instant traffic from Google within early months of blogging. Provide Controversy: There location special about controversies that make them great known. It is important to reach all audiences, those online and offline.

Hi Dear, are you really visiting this web site regularly, if so afterward you will absolutely obtain good experience.

Have you ever thought about publishing an e-book or guest authoring on other blogs? I have a blog centered on the same topics you discuss and would really like to have you share some stories/information. I know my readers would value your work. If you are even remotely interested, feel free to shoot me an e-mail.

It's just that if something can be searched, it could be searched. Sometimes you need to last the limb and branch your niche out. Anything that is put on function is content.

Do Genuinely want adjust? (E.g., Yes or no). When individual shop for a gift, one technique is to ensure that they will love the gift. Related applies to old coins any other coins in you collection.

I like the valuable info you provide in your articles. I'll bookmark your blog and check again here regularly. I am quite sure I'll learn many new stuff right here! Best of luck for the next!

Must take this activity something can perform experiment by using. So, don't forget your coupons and your particular shopping list. They convince themselves that they cannot do it again.

you are in reality a good webmaster. The web site loading velocity is amazing. It seems that you are doing any distinctive trick. Also, The contents are masterwork. you have done a magnificent activity in this matter!

They can a person what's possible and what's not they can. Following are a few very important tips on SEO that may be for you anytime. Submit some great work on various directories an individual can make sure.

Merveilleux blog! Je l'ai trouvé tout recherche sur Yahoo Nouvelles. Avez-vous des Conseils sur la façon d'obtenir la liste dans Yahoo Nouvelles? J'ai essayé pendant un certain temps, mais je ne semble jamais y arriver! Vive  my webpage: -

Hi there colleagues, its enormous piece of writing about tutoringand completely defined, keep it up all the time.

Everyone loves what you guys are usually up too. This sort of clever work and coverage! Keep up the terrific works guys I've added you guys to our blogroll.

We are a gaggle of volunteers and starting a new scheme in our community. Your site offered us with valuable information to work on. You have performed a formidable process and our whole community can be thankful to you.

I'm curious to find out what blog system you happen to be utilizing? I'm having some minor security issues with my latest website and I would like to find something more risk-free. Do you have any solutions?

I simply couldn't go away your site before suggesting that I really loved the standard info an individual provide for your visitors? Is gonna be back continuously to check out new posts

Hello Dear, are you genuinely visiting this site on a regular basis, if so after that you will absolutely get fastidious know-how.

First of all I would like to say fantastic blog! I had a quick question that I'd like to ask if you do not mind. I was curious to know how you center yourself and clear your head prior to writing. I have had difficulty clearing my mind in getting my ideas out. I do take pleasure in writing however it just seems like the first 10 to 15 minutes are lost just trying to figure out how to begin. Any suggestions or tips? Thanks!

Great delivery. Solid arguments. Keep up the good spirit.

Magnificent beat ! I wish to apprentice while you amend your site, how could i subscribe for a blog website? The account helped me a acceptable deal. I had been tiny bit acquainted of this your broadcast offered bright clear concept

What's up to all, how is the whole thing, I think every one is getting more from this web site, and your views are good in favor of new users.  Here is my blog post;  파워볼분석기 -

Hey! I just wanted to ask if you ever have any problems with hackers? My last blog (wordpress) was hacked and I ended up losing many months of hard work due to no backup. Do you have any solutions to prevent hackers?|

My partner and I stumbled over here by a different website and thought I might check things out. I like what I see so i am just following you. Look forward to finding out about your web page for a second time.

Oh my goodness! Amazing article dude! Thank you, However I am experiencing problems with your RSS. I don't understand the reason why I can't join it. Is there anybody else having identical RSS issues? Anyone that knows the answer will you kindly respond? Thanks!!

Hello would you mind stating which blog platform you're working with? I'm going to start my own blog in the near future but I'm having a difficult time selecting between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design and style seems different then most blogs and I'm looking for something unique.                  P.S Sorry for being off-topic but I had to ask!

There is sort of everyone on the internet that uses search engines for every query include. The quality of content plays a vital role whenever you high pr. This book covers the simple yet more efficient.

Kickboxing or additional class exercise would be considered a good concept. How A Simple Idea Taught me to be "Plant Manager Of The Year" follows the same attention grabbing formula. Bill Winter is employees member the boss.

Внимание как психологический процесс -

Greetings! Very helpful advice within this article! It is the little changes which will make the biggest changes. Many thanks for sharing!

Just a few posts from Jon himself have extra!

Hmm is anyone else encountering problems with the images on this blog loading? I'm trying to figure out if its a problem on my end or if it's the blog. Any feedback would be greatly appreciated.

Add comment

  • Comment
  • Preview

  • Contact Us
  • You can reach us at:
Copyright © Appvity 2015. All Rights Reserved.