Validate that file name before uploading a file to the SharePoint library!
In a course of time I’ve seen many ways to validate a name of a file which is being uploaded to the SharePoint library. It’s somehow not that well known that there is a SPEncode class in Microsoft.SharePoint.Utilities namespace which can really help us to implement the file name validation which covers all of the cases which SharePoint does not like.
Take a look at the SPEncode class. Hence, take a look at the whole Microsoft.SharePoint.Utilities namepace, there are some cool things there
For now a nice validation method based on it:
1: /// <summary>
2: /// Validates a file name before upload to the sharepoint library.
3: /// </summary>
4: /// <param name="fileName">Original file name</param>
5: /// <returns>Clean file name</returns>
6: private string cleanFileName(string fileName)
7: {
8: string ext = Path.GetExtension(fileName);
9: string name = Path.GetFileNameWithoutExtension(fileName);
10:
11: //
12: //first remove double fullstops (..)
13: while (name.Contains(".."))
14: {
15: name = name.Replace("..", "__");
16: }
17:
18: //
19: //name only is not allowed to end with fullstop (.)
20: if (name.EndsWith("."))
21: {
22: name = name.Substring(0, name.Length - 1) + "_";
23: }
24:
25: //
26: //now use "SPEncode.IsLegalCharInUrl()" to remove characters which sharepoint does not like
27: char[] filenameChars = name.ToCharArray();
28: foreach (char c in filenameChars)
29: {
30: if (!SPEncode.IsLegalCharInUrl(c)) name = name.Replace(c.ToString(), "");
31: }
32:
33: //
34: //return clean filename
35: return string.Format("{0}{1}", name, ext);
36: }



Hello,
Thanks for this tips. I would suggest an small enhancement.
The loop to replace each unauthorized char to “” has a n^2 complexity because the ‘string.Replace’ iterates through the entire string.
It would be a lot more efficient (n complexity) to do something like :
var result = new StringBuilder(name.Length);
foreach (var c in name.ToCharArray())
if (!SPEncode.IsLegalCharInUrl(c))
result.Append(c);
return result.ToString();
for a file name with 100 chars, you would do 100 operation instead of 10,000 ! And not to mention that you would use a lot less memory thanks to the stringbuilder
Tnx for the tip, Manitra
Cheers!