Search code examples
c#windowsfilenames

How to make a valid Windows filename from an arbitrary string?


I've got a string like "Foo: Bar" that I want to use as a filename, but on Windows the ":" char isn't allowed in a filename.

Is there a method that will turn "Foo: Bar" into something like "Foo- Bar"?


Solution

  • Try something like this:

    string fileName = "something";
    foreach (char c in System.IO.Path.GetInvalidFileNameChars())
    {
       fileName = fileName.Replace(c, '_');
    }
    

    Edit:

    Since GetInvalidFileNameChars() will return 10 or 15 chars, it's better to use a StringBuilder instead of a simple string; the original version will take longer and consume more memory.