views:

134

answers:

2

In C#, I have a filename that needs to converted to be double-escaped (because I feed this string into a regex).

In other words, if I have:

FileInfo file = new FileInfo(@"c:\windows\foo.txt");
string fileName = file.FullName;

fileName is: c:\\\\windows\\\\foo.txt

But I need to convert this to have sequences of two literal backslashes \\ in the fileName. fileName needs to be @"c:\\\\windows\\\\foo.txt", or "c:\\\\\\\\windows\\\\\\\\foo.txt". Is there an easy way to make this conversion?

A: 

simplest without resorting to regex for this part:

string fileName = file.FullName.Replace(@"\", @"\\\\");

based on OP, but I think you really want this:

string fileName = file.FullName.Replace(@"\", @"\\");

That being said, I can't see how you want to use it... it shouldn't need escaping at all... maybe you should post more code?

Luke Schafer
Ah, C# strings have a Replace method! :) That does the trick.
Drakestar
Oh, and I needed this for feeding that string into a regex. So the backslashes needed to be escaped.
Drakestar
+6  A: 

I Think you're looking for Regex.Escape

Regex.Escape(@"c:\test.txt") == @"C:\\Test\.txt"

notice how it also escapes '.'

Cipher