2

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??

4

Found the solution... Here's how I changed my code.

private void UploadAttachments(Helper sharePointHelper, IList<HttpPostedFile> postedFileCollection, int itemId)
{
    // Get the list
    SPList listToUpdate = Helper.GetList(this.BackendListName);
    SPListItem itemToUpdate = null;

    // Get the existing item to update
    itemToUpdate = listToUpdate.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);

        // Solution
        // Create the RegEx object with the pattern 
        Regex regEx = new Regex("[\~\#\%\&\*\{\}\\\:\<\>\?\/\+\|]");

        // Get the validated file name string
        string validatedFileName = regEx.Replace(fileName, "");

        // Attach the file (with the validated fileName string)
        itemToUpdate.Attachments.Add(validatedFileName, contents);
        itemToUpdate.SystemUpdate();
    }

}

The list of invalid characters was taken from Nikitin's answer.

Hope this will be helpful for others InshaALLAH :)!

| improve this answer | |
1

@Muhammedh's solution to use Regex is very good. Great Regex, but you can do better!

According to this support article from Microsoft not only are the special characters not allowed, but certain file extensions are also not allowed! And using _vti is not allowed either - so many restrictions!

Here's a Regex that takes all of them into account:

"^(\\W|_vti|_)|[^\\w]|(files|file|Dateien|fichiers|bestanden|archivos|filer|tiedostot|pliki|soubory|elemei|ficheiros|arquivos|dosyalar|datoteke|fitxers|failid|fails|bylos|fajlovi|fitxategiak)$"

Break it down:

// Matches any string that starts with a non-word character
// + any string that starts with '_vti'
// + any string that starts with an _ (underscore) (apparently this is a 'word character')
^(\\W|_vti|_)

// Matches any characters that are non-word characters
[^\\w]

// Matches all the illegal file endings listed in the support article.
(files|file|Dateien|fichiers|bestanden|archivos|filer|tiedostot|pliki|soubory|elemei|ficheiros|arquivos|dosyalar|datoteke|fitxers|failid|fails|bylos|fajlovi|fitxategiak)$

Example:

const string pattern = "^(\\W|_vti|_)|[^\\w]|(files|file|Dateien|fichiers|bestanden|archivos|filer|tiedostot|pliki|soubory|elemei|ficheiros|arquivos|dosyalar|datoteke|fitxers|failid|fails|bylos|fajlovi|fitxategiak)$";
const string str = "Doc with & opr.docx";
var regexedStr = Regex.Replace(str, pattern, string.Empty);

Yields result

Docwithoprdocx

| improve this answer | |
  • Thanks @daniel-ziga! I will have to use your RegEx to check during the FIleUpload itself and prompt for a new name, (Not after the List Item is added). Thanks again!! – Muhammedh Aug 5 '15 at 8:41
  • if I use this RegEx and do a match, it should even match & character yeah? I tried with the file name 'Doc with & opr.docx' and it did not match. Am I missing something? – Muhammedh Aug 6 '15 at 6:05
  • @Muhammedh Please see the example in my updated answer – user2536 Aug 6 '15 at 6:58
  • I want to check the extensions before upload and then if the extensions are good, I want to replace the characters and then attach to the SPListItem. Sorry If was not clear enough. – Muhammedh Aug 9 '15 at 7:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.