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);
}
?
The easiest way for removing special characters with the help of the FileRenamer is the function: Delete Character Groups -> Special Characters.
The backslash ( \ ) should be escaped. ( '[\\\\/*?:"<>|]' or r'[\\/*?:"<>|]' ). Otherwise backslashes will not be removed.
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()));
}
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();
}
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