Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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);
}

?

like image 994
Ruslan Avatar asked Feb 09 '10 16:02

Ruslan


People also ask

How do I remove special characters from a filename?

The easiest way for removing special characters with the help of the FileRenamer is the function: Delete Character Groups -> Special Characters.

How do I remove special characters from a filename in Python?

The backslash ( \ ) should be escaped. ( '[\\\\/*?:"<>|]' or r'[\\/*?:"<>|]' ). Otherwise backslashes will not be removed.


2 Answers

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()));

}
like image 164
Ceres Avatar answered Oct 29 '22 01:10

Ceres


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();
}
like image 41
JaredPar Avatar answered Oct 29 '22 02:10

JaredPar