1using System;
2using System.Text.RegularExpressions;
3
4namespace Misc
5{
6 public class Helper
7 {
8 public static string RemoveInvalidCharacters(string name)
9 {
10 if(name == null)
11 throw new ArgumentNullException("name");
12
13 //We should trim the input before we do length check.
14 //This way, we could be able to fit in more characters in
15 //our output if there are spaces in the beginning.
16 name = name.Trim();
17
18 string[] invalidCharacters =
19 new string[]
20 {
21 "#", "%", "&", "*", ":", "<", ">", "?", "\\", "/", "{", "}", "~", "+", "-", ",", "(", ")", "|",
22 "."
23 };
24
25 Regex cleanUpRegex = GetCharacterRemovalRegex(invalidCharacters);
26 string cleanName = cleanUpRegex.Replace(name, string.Empty);
27 cleanName = cleanName.Replace(" ", "%20");
28
29 if (cleanName.StartsWith("_"))
30 cleanName = cleanName.Substring(1);
31
32 if (cleanName.Length > 50)
33 cleanName = cleanName.Substring(0, 50);
34
35 return cleanName;
36 }
37
38 private static Regex GetCharacterRemovalRegex(string[] invalidCharacters)
39 {
40 if(invalidCharacters == null)
41 throw new ArgumentNullException("invalidCharacters");
42
43 if(invalidCharacters.Length == 0)
44 throw new ArgumentException("invalidCharacters can not be empty.", "invalidCharacters");
45
46 string[] escapedCharacters = new string[invalidCharacters.Length];
47
48 int index = 0;
49
50 foreach (string input in invalidCharacters)
51 {
52 escapedCharacters[index] = Regex.Escape(input);
53 index++;
54 }
55
56 return new Regex(string.Join("|", escapedCharacters));
57 }
58}
59
60}
61
62}