Here is a quick sample on how you can validate a file or folder name before creating/uploading it in SharePoint.
Scenario in which I used this code block when I am creating a folder hierarchy in SharePoint site (on-premises or online) based on a database query and migrating files.
Based on the KB 905231, there are following characters are not allowed in the file/folder name for SharePoint.
- Tilde (~)
- Number sign (#)
- Percent (%)
- Ampersand (&)
- Asterisk (*)
- Braces ({ })
- Backslash (\)
- Colon (:)
- Angle brackets (< >)
- Question mark (?)
- Slash (/)
- Plus sign (+)
- Pipe (|)
- Quotation mark (")
- You cannot use the period character consecutively in the middle of a file name.
- You cannot use the period character at the end of a file name.
- You cannot start a file name by using the period character.
- If you use an underscore character (_) at the beginning of a file name, the file will be a hidden file.
Extra conditions:
In addition, file names and folder names may not end with any of the following strings:
- .files
- _files
- -Dateien
- _fichiers
- _bestanden
- _file
- _archivos
- -filer
- _tiedostot
- _pliki
- _soubory
- _elemei
- _ficheiros
- _arquivos
- _dosyalar
- _datoteke
- _fitxers
- _failid
- _fails
- _bylos
- _fajlovi
- _fitxategiak
You can pass the required file/folder name which need to be validated to the function, and function will let you know if that is a valid name.
public static bool NameValidate(string strName)
{
bool isValidFileName = true;
var match = (new Regex("[ ~ # % & * { } : < > ? / + | \" \\\\ ]|\\.\\.|^\\.|^[_]|\\.$")).IsMatch(strName);
if (match)
{
//Invalid file name.
isValidFileName = false;
}else
{
//Valid file name.
}
return isValidFileName;
}
Else you can also use below options if you have to replace each occurrence of characters and fix the name –
char[] filenameChars = fileORFolderName.ToCharArray();
foreach (char c in filenameChars)
{
if (!SPEncode.IsLegalCharInUrl(c))
fileORFolderName = fileORFolderName.Replace(c.ToString(), "");
}
In above the reg ex can be broken as:
[ ~ # % & * { } : < > ? / + | \" \\\\ ] | Any one of the chars anywhere in the name (last \\\\ represent one backslash \) |
\\.\\. | . .( double Dot) consecutive dot occurring in the name |
^\\. | . (Dot) at the start of name |
^[_] | _(underscore) in the beginning of name |
\\.$ | . (Dot) at the end of name |
Feel free to share your comments.
No comments:
Post a Comment