The code snippet below replaces all invalid characters for a filename with Regex’ static Replace method;
/// <summary>
/// Replaces invalid path/file characters in given string with an underscore
/// </summary>
/// <param name="getString">string array to get string from CTX-Release</param>
/// <param name="lParamCount">number of parameteres which is set by CTX-Release while calling the function</param>
/// <returns>string with invalid characters replaced with underscore</returns>
public string ReplaceInvalidPathChars(object[] getString, int lParamCount)
{
string retValue = String.Empty;
if (getString.Length > 0)
{
retValue = getString[0].ToString();
char[] invalidChars = System.IO.Path.GetInvalidFileNameChars();
string invalidString = Regex.Escape(new string(invalidChars));
retValue = Regex.Replace(getString[0].ToString(), "[" + invalidString + "]", "_");
retValue = retValue.Replace(" ", "_");
}
return retValue;
}
(Source: C# in a Nutshell by Albahari)