Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace \ with \\ doesn't work for specific variable

Tags:

c#

backslash

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: Screenshot of code

like image 760
HackerNCoder Avatar asked Dec 17 '19 10:12

HackerNCoder


2 Answers

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.

like image 146
Heki Avatar answered Nov 11 '22 16:11

Heki


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");
like image 26
robbpriestley Avatar answered Nov 11 '22 18:11

robbpriestley