-3

I have the following code inside my c# application:-

 string[] excludechar = { "|", "\\", "\"", "'", "/", "[", " ]", ":", "<", " >", "+", "=", ",", ";", "?", "*", " @" };
 var currentgroupname = curItemSiteName;
 for (int i = 0; i < excludechar.Length; i++)
       {
         if (currentgroupname.Contains(excludechar[i]))
             currentgroupname.Replace(excludechar[i], "");       
       }
 site.RootWeb.SiteGroups.Add(currentgroupname)

now in my abive code the currentgroupname variable which i am passing inside the .ADD function will have all the special characters i have replaced inside my for loop. so can anyone adivce if i can modify my code so the .Replace will be actually replacing the original string of the currentgroupname ...

John John
  • 1
  • 72
  • 238
  • 501

2 Answers2

2

You are not actually assigning the "replaced" string to currentgroupname

 string[] excludechar = { "|", "\\", "\"", "'", "/", "[", " ]", ":", "<", " >", "+", "=", ",", ";", "?", "*", " @" };
 var currentgroupname = curItemSiteName;
 for (int i = 0; i < excludechar.Length; i++)
       {
         if (currentgroupname.Contains(excludechar[i]))
             currentgroupname = currentgroupname.Replace(excludechar[i], "");       
       }
 site.RootWeb.SiteGroups.Add(currentgroupname)
NicoRiff
  • 4,803
  • 3
  • 25
  • 54
0

Isn't it easier with some regex?

var input = "<>+--!I/have:many@invalid\\|\\characters";
var result = Regex.Replace(input, @"\W", "");
Console.Write(result); //Ihavemanyinvalidcharacters

Don't forget the using:

using System.Text.RegularExpressions;
Luis Lavieri
  • 4,064
  • 6
  • 39
  • 69