In Java, I've a File-Name-String. There I want to replace all illegal Characters with '_', but not a-z
, 0-9
, -
,.
and _
I tried following code: But this did not worked!
myString = myString.replaceAll("[\\W][^\\.][^-][^_]", "_");
You can simply use C# inbuilt function " Path. GetInvalidFileNameChars() " to check if there is invalid character in file name and remove it. var InvalidCharacters= Path. GetInvalidFileNameChars(); string GetInvalidCharactersRemovedString= new string(fileName .
The "Illegal characters" exception means that the file path string you are passing to ReadXml is wrong: it is not a valid path. It may contain '?' , or ':' in the wrong place, or '*' for example. You need to look at the value, check what it is, and work out where the illegal character(s) are coming from.
illegal character Any character not in the character set of a given machine or not allowed by a given programming language or protocol. A Dictionary of Computing.
You need to replace everything but [a-zA-Z0-9.-]
. The ^
within the brackets stands for "NOT".
myString = myString.replaceAll("[^a-zA-Z0-9\\.\\-]", "_");
If you are looking for options on windows platform then you can try below solution to make use of all valid characters other than "\/:*?"<>|" in file name.
fileName = fileName.replaceAll("[\\\\/:*?\"<>|]", "_");
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