So I’ve developed an automation tool using C# to print out InfoPath documents from my SharePoint Document Library. Here are the steps on how my is printing:
- Capture the path of the infopath document. e.g. http://mysharepointsite/form/form1.xml
- Create an instance of “Microsoft.Office.Interop.InfoPath.Application”
- Open the infopath document using the instance
- Used the instance’s XDocument.PrintOut() function.
- Used Thread.Sleep() to put a gap in between closing and opening a new form.
- Close the instance.
It works fine at times but sometimes when my software testers run my program, the program would randomly stop in the middle of printing. I’ve captured the logs and found that it was throwing this error:
Creating an instance of the COM component with CLSID {8075535F-5146-11D5-A672-00B0D022E945} from the IClassFactory failed due to the following error: 80010108.
It happened whenever I had multiple forms printed out. It seems that the threading interval wasn’t enough at times. So I’ve added code that called a recursive function to check whether an InfoPath instance is still running and add interval to the sleep thread.
So I would like to share this code since there isn’t much about this out there, hope it helps!
//Print Method
private static void PrintForm(string sourceDocument)
{
Microsoft.Office.Interop.InfoPath.Application appIP=null;
object varIndex = null;
try
{
//Check if an instance of InfoPath is already running.
WaitForInfoPathToEnd();
appIP = new Microsoft.Office.Interop.InfoPath.Application();
varIndex = appIP.XDocuments.Open(sourceDocument, (int)Microsoft.Office.Interop.InfoPath.XdDocumentVersionMode.xdUseExistingVersion);
if (appIP.XDocuments.Count > 0)
{
appIP.Windows[0].XDocument.PrintOut();
}
}
catch (Exception ex)
{
//Do something
}
finally
{
Thread.Sleep(4000);
if (varIndex != null)
appIP.XDocuments.Close(varIndex);
Thread.Sleep(2000);
if (appIP != null)
{
appIP.Quit(true);
appIP = null;
}
}
}
//Check if an instance of infopath instance is still running
private static void WaitForInfoPathToEnd()
{
Process[] processes = Process.GetProcessesByName("INFOPATH");
if (processes.Length > 0)
{
Thread.Sleep(4000);
WaitForInfoPathToEnd();
}
}


