views:

328

answers:

2

Hello everyone. Can anyone please suggest a way to replace back-slash '\' with slash '/' in a string. Basically the string is a path. I have tried using Replace() method of string, but its not working.

Thanks

+9  A: 

You'll need to capture the result of the Replace (strings are immutable), and ensure you use character-escaping for the \:

string path = Directory.GetCurrentDirectory();
path = path.Replace("\\", "/");

For info; most of the inbuilt methods will accept either, and assuming you are on Windows, \ would be more common anyway. If you want a uri, then use a Uri:

string path = Directory.GetCurrentDirectory();
Uri uri = new Uri(path); // displays as "file:///C:/Users/mgravell/AppData/Local/Temporary Projects/ConsoleApplication1/bin/Debug"
string abs = uri.AbsolutePath; // "C:/Users/mgravell/AppData/Local/Temporary%20Projects/ConsoleApplication1/bin/Debug"
Marc Gravell
You need sitePath =sitePath.Replace("\\", "/"); as .Replace createa a new instance
JDunkerley
I think you need to do the following: sitePath = sitePath.Replace("\\", "/"); This is what Marc means when he says strings are immutable, calling a function does not change the value of the string, the function returns a new string.
Oplopanax
Thanks a lot. I was missing the point that String are immutable.
kobra
Thanks a lot. You have answered all my questions.
kobra
+1  A: 

This is only slightly related, but I like to mention it when I see the \ character being used; just in case some are unaware.

Note that C# has a syntax escape character, the @ symbol. You can use it to escape reserved words, but more often, you'll use it to escape string literal escape sequences.

For example, if you're going to use the \ character in a literal and don't want to have to escape it with another \, you can prefix the literal with @. Thus the above code could be written like:

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

I find it very helpful when working with file paths:

var path = "C:\\Documents and Settings\\My Documents\\SomeFile.txt";

can be written as:

var path = @"C:\Documents and Settings\My Documents\SomeFile.txt";

It helps the readability.

Travis Heseman