Search code examples
c#stringreplacestring-literals

replace single backslash in database driven string


This might seem like a question that's been answered many times. My team and I have tried many solutions over the past hour without any luck. We have a database driven string value that contains c:\test and we want to replace the backslash with \\ resulting in c:\\test.

We've tried using .Replace, Regex.Replace, .Split and rebuilding the string, I tried using a for loop and substring to examine each character. When you get past the colon the next character shows up as "\t".

Please try the solution before submitting as we've tried a lot of different methods including dozens of suggestions already on stack overflow.

If we manually set the string as a literal like path = @"c:\test" then using replace works fine.

I would think that the solution would be to create a string that doesn't process the escape character but I have no idea how to implement that.


Solution

  • Sounds like your string already contains "tab" character ('\t') you probably need to replace it with "\\t" :

    var result = "c:\test".Replace("\t", "\\t");