The best way is: never concatenate strings to form SQL queries. If you always use parametrised queries, then you leave nothing open to SQL Injection attack, and you don't have to change any characters.
Having said that, the way you are doing things is very inefficient:
1) Use a
StringBuilder
instead of a string to assemble strings from parts. Strings are immutable: they cannot be changed after they are constructed, so each time you add a character you generate a new string a character longer than it was and copy the data over. This is a very, very inefficient way to do it!
2) You don't need local data for your comparison array - use a class level
static
instead, and it is constructed once, instead of each time the method is called.
3) If you use a
List
instead of an
array
, it has a
Contains
method!
4) If you use
char
instead of
string
for your comparison anyway, you don't need to waset time with unecesary ToString calls:
private static char[] Valid_Chars = new char[] {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z' };
private static List<char> valid = new List<char>(Valid_Chars);
static public string MakeSafeData(string Unsafe_String)
{
StringBuilder sb = new StringBuilder();
foreach (char c in Unsafe_String)
{
if (valid.Contains(c) || valid.Contains(char.ToLower(c)))
{
sb.Append(c);
}
}
return sb.ToString();
}
[edit]Should have been ToLower not ToUpper to match characters in compare list - OriginalGriff[/edit]