Reputation: 4963
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
Upvotes: 3
Views: 9472
Reputation: 11449
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.
Upvotes: 1
Reputation: 1062745
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"
Upvotes: 10