Sometimes, I need to create files or folders directly, and use existing data to provide the file name.
That’s all about how to remove all special characters from String in C#. As I said, you can use Replace() method of String along with regular expression to get rid of unwanted characters. You can define characters you want or remove in the regular expression as shown in our example.
1 2 3 4 5 6 7 8 9 |
private static string MakeValidFileName(string name) { string invalidChars = System.Text.RegularExpressions.Regex.Escape(new string(System.IO.Path.GetInvalidFileNameChars())); string invalidRegStr = string.Format(@"([{0}]*\.+$)|([{0}]+)", invalidChars); return System.Text.RegularExpressions.Regex.Replace(name, invalidRegStr, "_"); } |