Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# string.replace to remove illegal characters [duplicate]

Tags:

string

c#

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.

like image 566
Axxelsian Avatar asked Jun 05 '12 13:06

Axxelsian


1 Answers

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);
}
like image 62
canon Avatar answered Oct 17 '22 04:10

canon