Programmatically uploading an InfoPath form to a SharePoint document library

In this case I am using the viewswitched event captured in the form “code behind” but this means I had to publish the form as an Administrator-approved template and upload it into Central Admin.  There are a few ways to code this but here I am using the SharePoint object model. I use the RunWithElevatedPrivileges call to execute the code under the application pool account. This is relevant because I am allowing annonymous users to “submit” the form to SharePoint.

public void FormEvents_ViewSwitched(object sender, ViewSwitchedEventArgs e)
        SPSecurity.RunWithElevatedPrivileges(delegate() {

         EventLog _eventLog;
            _eventLog = new EventLog(“Application”);
            _eventLog.Source = “InfoPath Form Upload”;

            XPathNavigator xPathNav = MainDataSource.CreateNavigator();
            string name = xPathNav.SelectSingleNode(“/my:MessageSection/my:hiddenName”, NamespaceManager).InnerXml;
             string webappurl = this.Template.Uri.ToString().Remove(0, 7);
            webappurl = webappurl.Split(‘/’)[0];
           string url = “http://” + webappurl + “/FormLibrary/” + name + “.xml”;                   

            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();

           byte[] Data = encoding.GetBytes(xPathNav.OuterXml);


                 SPSite mySiteCollection = new SPSite(http://sitecollurl);
                SPWeb myWeb = mySiteCollection.RootWeb;    
                SPFolder doclib = myWeb.Folders[“Form Library”];
                SPFile file = doclib.Files.Add(doclib.Url + “/” +
                      name + “.xml”, Data, true);

            catch (Exception ex)
                _eventLog.WriteEntry(“Form Upload Failed ” + ex.Message);


Leave a Reply

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

You are commenting using your 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