I'm working on a program that reads files and saves pieces of them according to their column's title. Some of those titles have illegal characters for file names, so i've written this piece of code to handle those issues.
string headerfile = saveDir + "\\" + tVS.Nodes[r].Text.Replace("\"", "").Replace
("/","").Replace(":"," -").Replace(">","(Greater Than)") + ".csv";
Is there a nicer way of doing this where i don't have 4 .Replace()
? or is there some sort of built in illegal character remover i don't know of?
Thanks!
EDIT: It does not need to replace the characters with anything specific. A blank space is sufficient.
System.IO.Path.GetInvalidFileNameChars()
has all the invalid characters.
Here's a sample method:
public static string SanitizeFileName(string fileName, char replacementChar = '_')
{
var blackList = new HashSet<char>(System.IO.Path.GetInvalidFileNameChars());
var output = fileName.ToCharArray();
for (int i = 0, ln = output.Length; i < ln; i++)
{
if (blackList.Contains(output[i]))
{
output[i] = replacementChar;
}
}
return new String(output);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With