-1

I am working in asp.net mvc. want to replace \ character to / character. But it is not working. Let

string path="D:\Qamar\Cartoons\Image.jpg";
path=path.Replace("\","/");

I get error in second line. Please help how to replace.

Fakhar uz Zaman
  • 191
  • 6
  • 22
  • http://stackoverflow.com/questions/4673437/c-sharp-replace-characters might help you. – Mogli May 15 '13 at 07:32
  • _"I get error in second line."_ - it would be nice if you explained what kind of error. It's not the replace that's not working, you get a compile error. – CodeCaster May 15 '13 at 07:47

5 Answers5

4

Try this:

string path="D:\Qamar\Cartoons\Image.jpg";
path=path.Replace("\\","/");

You need to escape the backslash in the first argument for it to be treated as...a backslash (i.e. "\\" instead of "\").

J0e3gan
  • 8,740
  • 10
  • 53
  • 80
1

You need to escape back-slashes. The easiest way is to prefix your string with @:

path=path.Replace(@"\","/");

Another method is to escape it with another backslash:

path=path.Replace("\\","/");
Kenneth
  • 28,294
  • 6
  • 61
  • 84
1

try this

th=path.Replace("\\","/")
Raver0124
  • 512
  • 2
  • 9
0

\ is a special escape character in string literals in c#. You can precede the string with @ to make it verbatim or escape the \ with another \:

path=path.Replace(@"\","/");

or

path=path.Replace("\\","/");
Jan
  • 15,802
  • 5
  • 35
  • 59
0

\ is escape character, so your code will not even compile use @ or \\ to make the code compile. then it will work

string path=@"D:\Qamar\Cartoons\Image.jpg";
path=path.Replace(@"\","/");

or

string path="D:\\Qamar\\Cartoons\\Image.jpg";
path=path.Replace("\\","/");

but if you are working with Path or URI you can use the inbuilt C# methods to do it like below

System.Uri uri1 = new Uri(@"D:\Qamar\Cartoons\Image.jpg");
string whatYouWant = uri1.AbsolutePath; //Result is: "D:/Qamar/Cartoons/Image.jpg"
Damith
  • 62,401
  • 13
  • 102
  • 153