if (String.IsNullOrEmpty(str)) return str; string okChars = "abcdefghijklmnopqrstuvwxyz1234567890 _-"; str = str.Trim().ToLowerInvariant(); var sb = new StringBuilder(); foreach (char c in str.ToCharArray()) { string c2 = c.ToString(); if (okChars.Contains(c2)) sb.Append(c2); } string str2 = sb.ToString(); str2= str2.Replace(" ", "_"); str2= str2.Replace("-", "_"); while (str2.Contains("__")) str2 = str2.Replace("__", "_"); return str2;