1. 程式人生 > >C# 去除字串中的非法字元

C# 去除字串中的非法字元

/// <summary>
/// 檢查是否含有非法字元
/// </summary>
/// <param name="str">要檢查的字串</param>
/// <returns></returns>
public static bool ChkBadChar(string str)
{
 bool result = false;
 if (string.IsNullOrEmpty(str))
 return result;
 string strBadChar, tempChar;
 string[] arrBadChar;
 strBadChar = "@@,+,',--,%,^,&,?,(,),<,>,[,],{,},/,\\,;,:,\",\"\"";
 arrBadChar = SplitString(strBadChar, ",");
 tempChar = str;
 for (int i = 0; i < arrBadChar.Length; i++)
 {
 if (tempChar.IndexOf(arrBadChar[i]) >= 0)
 result = true;
 }
 return result;
}

/// <summary>
/// 過濾非法字元
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ReplaceBadChar(string str)
{
 if (string.IsNullOrEmpty(str))
 return "";
 string strBadChar, tempChar;
 string[] arrBadChar;
 strBadChar = "@@,+,',--,%,^,&,?,(,),<,>,[,],{,},/,\\,;,:,\",\"\"";
 arrBadChar = SplitString(strBadChar, ",");
 tempChar = str;
 for (int i = 0; i < arrBadChar.Length; i++)
 {
 if (arrBadChar[i].Length > 0)
 tempChar = tempChar.Replace(arrBadChar[i], "");
 }
 return tempChar;
}


/// <summary>
/// 替換sql語句中的有問題符號
/// </summary>
public static string ReplaceBadSQL(string str)
{
 string str2 = "";
 if (string.IsNullOrEmpty(str))
 {
 return "";
 }
 string str1 = str;
 string[] strArray = new string[] { "'", "--" };
 StringBuilder builder = new StringBuilder(str1);
 for (int i = 0; i < strArray.Length; i++)
 {
 str2 = builder.Replace(strArray[i], "").ToString();
 }
 return builder.Replace("@@", "@").ToString();
}