I have been coding small utility for my own use. This utility is about parsing rss feeds and juggling with files. Names of the files come from feed, so I may get anything. This project is also a learning project for C# and .NET, so it is not always clear how to achieve certain outcomes.
A problem I faced with file names is that they can contain illegal characters and therefore I would have to strip or replace illegal characters from the original string. How can this be done using C#? The answer is Regular expressions. Just by looking the example below you will see how versatile C# really is.
[scode]
public static string ValidFilenameFromString(string name)
{
string invalidChars = Regex.Escape(new string(Path.GetInvalidFileNameChars()));
string invalidRegexpStr = string.Format(@”[{0}]+”, invalidChars);
return Regex.Replace(name, invalidRegexpStr, “_”);
}
[/scode]