Remove invalid (disallowed, bad) characters from FileName (or Directory, Folder, File)

I’ve wrote this little method to achieve the goal in the subj., however, is there more efficient (simpler) way of doing this? I hope this can help somebody who will search for this like I did.

var fileName = new System.Text.StringBuilder();
fileName.Append("*Bad/ :, Filename,? ");
// get rid of invalid chars
while (fileName.ToString().IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) > -1)
{
    fileName = fileName.Remove(fileName.ToString().IndexOfAny(System.IO.Path.GetInvalidFileNameChars()), 1);
}

?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I know this is a few years old but here is another solution for reference.

public string GetSafeFilename(string filename)
{

    return string.Join("_", filename.Split(Path.GetInvalidFileNameChars()));

}

Method 2

Try the following

public string MakeValidFileName(string name) {
  var builder = new StringBuilder();
  var invalid = System.IO.Path.GetInvalidFileNameChars();
  foreach ( var cur in name ) {
    if ( !invalid.Contains(cur) ) {
      builder.Append(cur);
    }
  }
  return builder.ToString();
}

Method 3

A different approach that is compatible with .NET 4. See my comments above explaining the need.

public static string ScrubFileName(string value)
{
   var sb = new StringBuilder(value);
   foreach (char item in Path.GetInvalidFileNameChars())
   {
      sb.Replace(item.ToString(), "");
   }
   return sb.ToString();
}

Method 4

If you look for “concise” when you say simple:

public string StripInvalidChars(string filename) {
  return new String(
    filename.Except(System.IO.Path.GetInvalidFileNameChars()).ToArray()
  );
}

That said, I’d go with JaredPar’s solution. It’s probably easier to read (depending on taste, background), my gut feeling is that it is more efficient (although I’m not sure how efficient you have to be stripping that dozen of invalid chars from a limited length filename) and his use of a StringBuilder() seems to fit perfectly to your example.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x