Replacing from a list chars in a string Often I need to clean a file name using Path.GetInvalidFileNameChars(), however I do not know of a way to search for any of the invalid letters (except by using Regex) in one pass.

public string LoopMethod()
{
    StringBuilder sb = new StringBuilder(fileName);
    foreach(var invalidChar in Path.GetInvalidFileNameChars())
    {
        sb.Replace(invalidChar, '_');
    }
    return sb.ToString();
}


Regex invalidCharsRegex;
public void RegexMethodInit()
{
    var invalidChars = Path.GetInvalidPathChars().Select(c =&gt; Regex.Escape(c.ToString())).ToString();
    invalidCharsRegex = new Regex(string.Join("|", invalidChars));
}

public string RegexMethod(string fileName)
{
    return invalidCharsRegex.Replace(fileName, "_");
}


Is one of those ways the "correct" way to to this or is there a better function I am missing?
foreach(var c in Path.GetInvalidPathChars())
    path = path.replace(c, '_')


That's a bit inefficient as it can allocate a string on every itteration, but usually not a problem. Alternative:

var chars = Path.GetInvalidPathChars()
path = new string(path.Select(c =&gt; chars.Contains(c) ? '_' : c).ToArray())