Remove illegal characters from file name or file path in c#

File cannot be saved if file name has illegal characters. So how to remove the illegal characters by a single line code as below. I use LINQ Querty for that.


string fileName = "prakash C/O swami.xml";
fileName = System.IO.Path.GetInvalidFileNameChars().Aggregate(fileName, (current, c) => current.Replace(c.ToString(), string.Empty));

Now the fileName is “rakash CO swami.xml”. The code removes slash ‘/’ because it is a illegal characters. As same any illegal characters will remove using this above code.

Share