If you find yourself having to strip illegal chars from user input, as I have found myself doing on numerous occasions when dealing with files and directory paths in Unity, it is always a good idea to have a method/function handy and at the ready, there are of course many ways to do this and I know that some would lean towards Regex as I have also done in the past, but here’s my adapted unity 3d – c# .net offering that also does what it says on the tin.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public static string RemoveInvalidFilenameCharacters(string filename) { int i; if (!string.IsNullOrEmpty(filename)) { List invalidchars=new List(); invalidchars.AddRange(""#%&*/:<>?\{|}~".ToCharArray()); invalidchars.AddRange(System.IO.Path.GetInvalidPathChars()); invalidchars.AddRange(System.IO.Path.GetInvalidFileNameChars()); invalidchars.AddRange(new char[]{System.IO.Path.PathSeparator,System.IO.Path.AltDirectorySeparatorChar}); for(i=0;i<invalidchars.Count;++i) { filename = filename.Replace(invalidchars[i].ToString(), string.Empty); } } return filename; } |
12256 Total Views 5 Views Today
I use the below options:
private static string GetValidFileName(string fileName)
{
// remove any invalid character from the filename.
return Regex.Replace(fileName.Trim(), “[^A-Za-z0-9_. ]+”, “”);
}
private static string GetValidFileName(string fileName)
{
return Path.GetInvalidFileNameChars().Aggregate(fileName, (current, c) => current.Replace(c.ToString(), string.Empty));
}
Its explained in this post:
http://codeskaters.blogspot.ae/2013/11/c-remove-invalid-filename-characters.html
Thanks Habeeb, just got round to admin, great comment!