Wednesday, November 22, 2017

Remove/Replace invalid characters in string (c# / .NET)


To remove/replace invalid characters in a string, try implementing the below function. filename is the name of file and replaceChar is the character that you want to replace with the invalid characters.


private string RemoveInvalidFilePathCharacters(string filename, string replaceChar)
        {
            string regexSearch = new string(System.IO.Path.GetInvalidFileNameChars()) + new string(System.IO.Path.GetInvalidPathChars());
            System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(string.Format("[{0}]", System.Text.RegularExpressions.Regex.Escape(regexSearch)));
            return r.Replace(filename, replaceChar);
        }

No comments:

Post a Comment