Creating new files in a Document Library is a pretty simple task as copying the template located in the "Forms" folder. But creating a new Form is a bit harder as the template is a binary file, and what we want is a new Xml file.
The template file (with extension XSN) created by InfoPath is actually a CAB archive, that contains your form logic compiled, schemas and your xml template. So what you have to do is extract the CAB file, and copy the "template.xml" file to your Form Library. You can find a CAB extractor at The Code Project.
Here is a example of a method to get the template Xml:
private byte[] GetXmlForm(SPDocumentLibrary list) {
byte[] data = null;
SPFile file = list.ParentWeb.GetFile(list.DocumentTemplateUrl);
Extract cab = new Extract();
string szFolder = string.Concat(System.IO.Path.GetTempPath(), list.Title, "\\");
if( !Directory.Exists(szFolder) )
Directory.CreateDirectory(szFolder);
cab.ExtractStream(file.OpenBinaryStream(), szFolder);
FileStream fs = new FileStream(szFolder + "template.xml", FileMode.Open);
try {
data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
} finally {
fs.Close();
}
return data;
}
There is one more thing that has to be done before saving the template, which is to add a hyperlink to your InfoPath Template. The href should be added in the processing instruction tag "mso-infoPathSolution" ie.
<?mso-infoPathSolution href="http://server/site/library/Forms/myTemplate.xsn" ?>
Here is a snippet on how to do it:
frm.SetTemplateUrl("http://Server/Site/{0}"+list.DocumentTemplateUrl);
public void SetTemplateUrl(string url) {
foreach(XmlNode n in m_Doc.ChildNodes) {
if(n.Name == "mso-infoPathSolution") {
string szHref = string.Format("href=\"{0}\"", url);
Regex r = new Regex("href=\".*\"");
if(r.IsMatch(n.Value))
n.Value = r.Replace(n.Value, szHref);
else n.Value = string.Concat(n.Value,szHref,' ');
}
}
}