Scenario: I have a fileupload control in my custom webpart that attaches the uploaded files to the list item. The attachment code is given below:
private void UploadAttachments(Helper sharePointHelper, IList<HttpPostedFile> postedFileCollection, int itemId)
{
// Get the list
SPList spList = Helper.GetList(this.BackendListName);
SPListItem itemToUpdate = null;
// Get the existing item to update
itemToUpdate = spList.GetItemById(itemId);
foreach (HttpPostedFile postedFile in postedFileCollection)
{
Stream fileStream = postedFile.InputStream;
byte[] contents = new byte[fileStream.Length];
fileStream.Read(contents, 0, (int)fileStream.Length);
fileStream.Close();
fileStream.Dispose();
string fileName = Path.GetFileName(postedFile.FileName);
// Attach the file
itemToUpdate.Attachments.Add(fileName, contents);
itemToUpdate.SystemUpdate();
}
}
When I uploaded a document with the '&' character, I got the following error logged in my SP Logs.
Message: The file or folder name contains characters that are not permitted. Please use a different name.
Inner Exception: System.Runtime.InteropServices.COMException (0x81020073): The file or folder name contains characters that are not permitted. Please use a different name.<nativehr>0x81020073</nativehr><nativestack></nativestack>
at Microsoft.SharePoint.Library.SPRequestInternalClass.AddOrUpdateItem(String bstrUrl, String bstrListName, Boolean bAdd, Boolean bSystemUpdate, Boolean bPreserveItemVersion, Boolean bPreserveItemUIVersion, Boolean bUpdateNoVersion, Int32& plID, String& pbstrGuid, Guid pbstrNewDocId, Boolean bHasNewDocId, String bstrVersion, Object& pvarAttachmentNames, Object& pvarAttachmentContents, Object& pvarProperties, Boolean bCheckOut, Boolean bCheckin, Boolean bUnRestrictedUpdateInProgress, Boolean bMigration, Boolean bPublish, String bstrFileName, ISP2DSafeArrayWriter pListDataValidationCallback, ISP2DSafeArrayWriter pRestrictInsertCallback, ISP2DSafeArrayWriter pUniqueFieldCallback)
at Microsoft.SharePoint.Library.SPRequest.AddOrUpdateItem(String bstrUrl, String bstrListName, Boolean bAdd, Boolean bSystemUpdate, Boolean bPreserveItemVersion, Boolean bPreserveItemUIVersion, Boolean bUpdateNoVersion, Int32& plID, String& pbstrGuid, Guid pbstrNewDocId, Boolean bHasNewDocId, String bstrVersion, Object& pvarAttachmentNames, Object& pvarAttachmentContents, Object& pvarProperties, Boolean bCheckOut, Boolean bCheckin, Boolean bUnRestrictedUpdateInProgress, Boolean bMigration, Boolean bPublish, String bstrFileName, ISP2DSafeArrayWriter pListDataValidationCallback, ISP2DSafeArrayWriter pRestrictInsertCallback, ISP2DSafeArrayWriter pUniqueFieldCallback)
I want to change the name to valid name by replacing the invalid characters to "" and then save the file as the attachment.
I am guessing RegEx will be helpful. Thoughts??