public void UploadCaseAttachmentButton_Clicked(object sender, ClickedEventArgs e) { WriteToDebug("Upload Case Attachment Button Clicked"); UploadCaseAttachments(); SaveCase(); } private void UploadCaseAttachments() { WriteToDebug("Uploading Case Attachments..."); XPathNodeIterator caseAttachments = this.MainDataSource.CreateNavigator().Select("/my:myFields/my:Details/my:Attachment", NamespaceManager); if (caseAttachments != null) { { string attachmentFile = caseAttachments.Current.SelectSingleNode("my:AttachmentFile", NamespaceManager).Value; string attachmentDescription = caseAttachments.Current.SelectSingleNode("my:AttachmentDescription", NamespaceManager).Value; if (attachmentFile != null && !string.IsNullOrEmpty(attachmentFile)) { // Decode the InfoPath file attachment InfoPathAttachmentDecoder dec = new InfoPathAttachmentDecoder(attachmentFile); string fileName = dec.Filename; WriteToDebug(string.Format("Uploading case attachment file: {0}", fileName)); byte[] data = dec.DecodedAttachment; // Add the file to a document library using (SPSite site = new SPSite(SPContext.Current.Site.ID)) { using (SPWeb web = site.OpenWeb()) { web.AllowUnsafeUpdates = true; site.AllowUnsafeUpdates = true; SPList docLib = web.Lists["Case Attachments"]; SPFile file = web.Files.Add(docLib.RootFolder + "/" + fileName, data, true); file.Item["Title"] = attachmentDescription; file.Item["Case Id"] = GetCaseId(); SPFieldUrlValue linkValue = new SPFieldUrlValue(); linkValue.Description = fileName; linkValue.Url = string.Format("{0}/Lists/Case%20Attachments/{1}", web.Url, HttpUtility.UrlEncode(fileName).Replace("+", "%20")); file.Item["Link"] = linkValue; file.Item.Update(); web.AllowUnsafeUpdates = false; site.AllowUnsafeUpdates = false; web.Close(); } site.Close(); } } else { WriteToDebug("Removing empty attachment"); caseAttachments.Current.DeleteSelf(); } } int attachmentCount = caseAttachments.Count; if (attachmentCount > 0) { XPathNavigator firstAttachment = MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:Details/my:Attachment[1]", NamespaceManager); XPathNavigator lastAttachment = MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:Details/my:Attachment[" + attachmentCount.ToString() + "]", NamespaceManager); firstAttachment.DeleteRange(lastAttachment); } this.DataConnections["Case Attachments"].Execute(); } }