I am trying to replace a \
with \\
and it works with everything except the specific variable I need it to work on. Throwing the error Illegal characters in path.
probably because it thinks \t is a character, which is tab and is therefor not allowed in a path
the variable is loaded in from a json file using Newtonsoft.Json in to a class
public class WebsiteConfig
{
public string Name { get; set; }
public string Directory { get; set; }
}
I have tried
var escapedir = Regex.Replace(Directory, @"\\", @"\");
and any possible way I could form var escapedir = Directory.Replace("\", "\\");
.
Trying Regex.Replace("C:\test", @"\", @"\\");
(C:\test being the exact same as in Directory) worked perfectly and then inside a foreach I am trying to combine the Directory with a filename.
"Dump" of current code:
var json = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "config.json"));
_config = JsonConvert.DeserializeObject<Config>(json);
foreach(WebsiteConfig website in _config.WebsiteConfigList)
{
for (int i = 0; i <= 9; i++)
{
string dir = website.Directory;
string escapedir = Regex.Replace(dir, @"\\", @"\\\\");
var path = Path.Combine(escapedir, "Backedup_" + i.ToString() + ".txt");
}
}
And config.json:
{
"WebsiteConfigList": [
{
"Name": "test",
"Directory": "C:\test"
}
]
}
Here's a screenshot to show the exception:
The problem does indeed originate with \t
but it happens during deserialisation and not with the Path
as you might believe. There have been multiple suggestions to replace the backslash with an escaped backslash, but at that point the damage was already done:
The C:\test
had become C: est
(whitespace is a tab char).
As per your requirement, altering the input file is not an option, so you have to do your escaping before deserialisation. The simplest way I can think of is:
json = json.Replace(@"\", @"\\");
By the way, while Regex.Replace
is quite powerfull, string.Replace
is adequate.
It doesn't look like you have large JSON files, but if you do, read a bit here on string.Replace
on large files.
If you can't change the source JSON to be "C:\\test"
instead of "C:\test"
then detect the tab and replace it with what you want
string escapedir = Regex.Replace(dir, @"\t", @"\\\\t");
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