A Practical Guide to SharePoint 2013

A Practical Guide to SharePoint 2013
A Practical Guide to SharePoint 2013 - Book by Saifullah Shafiq

Tuesday, January 15, 2008

InfoPath: Delete file attachments programmatically (C#)

There is a section in your form that file attachment control or you can have attachment controls in a repeating table to allow multiple attachments and if you want to delete the file attachments using C#, here is the solution:
   XPathNavigator files = this.CreateNavigator().SelectSingleNode("/my:myFields/my:RepeatingGroup/my:FileAttachments", this.NamespaceManager);
                    XPathNodeIterator Node_2b_Deleted = this.CreateNavigator().Select("/my:myFields/my:RepeatingGroup/my:FileAttachments", NamespaceManager);
                    string attachments = "/my:myFields/my:RepeatingGroup/my:FileAttachments";
                    XPathNavigator firstItem;
                    XPathNavigator lastItem;
                    if (Node_2b_Deleted.Count > 1)
                    {
                        firstItem = files.SelectSingleNode(attachments + "[1]", NamespaceManager);
                        lastItem = files.SelectSingleNode(attachments + "[position()=last()]", NamespaceManager);
                        firstItem.DeleteRange(lastItem);
                        lastItem = null;
                        firstItem = null;
                    }
                    else if (Node_2b_Deleted.Count == 1)
                    {
                        firstItem = files.SelectSingleNode(attachments + "[1]", NamespaceManager);
                        firstItem.DeleteSelf();
                    }

                    Node_2b_Deleted = null;
                }
You define the XPath that points to the file attachments. You take the first node (attachments[1]) and the last node (attachments[position=last()] and delete the attachments:
firstItem.DeleteRange(lastItem); where first item points to the first node and lastItem points to the last node. If there are more than 1 attachment, then DeleteRange() is used but if there is only attachment, then you can use DeleteSelf() to remove the only node.
That's it. Confusion? Contact me!