tags:

views:

155

answers:

4

I have a local file path containing "\" and I need to change all occurrences to "/" for a remote file path.

I have tried

myString.replace("\","/")

and

myString.replace(Convert.ToChar(92), Convert.ToChar(47)) 

Both seem to leave the "\" in tact..

Answer:

NewString = myString.replace("\","/")

The problem was that I was not assigning it to a variable. Escaping the slash actually made it fail, in vb.net at least.

+4  A: 

\ has to be escaped, by prefixing it with another \ or by turning the complete string into an native string by prefixing the string with @. Furthermore, myString.replace does not alter myString (strings are immutable, i.e. cannot be changed), so you need to assign the value to see the result.

Use

string myNewString = myString.replace("\\","/")

or

string myNewString = mmyString.replace(@"\","/")

or

string myNewString = mmyString.replace('\\','/')
Obalix
the "\" is a special character, so you have to escape it using "\"
David
You only need to escape in C~ - VB.Net, which appears to be the language being used, doesn't require this.
Martin Milan
A: 

You can escape the \:

myString.replace("\\","/")

Or use a string literal (C#):

myString.replace(@"\","/")

Or use the overload that uses chars:

myString.replace('\','/')
Oded
Wrong direction of the slash in the first line ... :-)
Obalix
@Obalix - quite right. corrected.
Oded
A: 

You need to escape the back slash (\) with an extra back slash (\\) , try this:

myString.replace("\\","/")
Sarfraz
+6  A: 

Strings are immutable. The Replace method returns a new string rather than affecting the current string, therefore you need to capture the result in a variable. If you're using VB.NET there's no need to escape the backslash, however in C# it must be escaped by using 2 of them.

VB.NET (no escaping needed):

myString = myString.Replace("\","/")

C# (backslash escaped):

myString = myString.Replace("\\","/");

I assume you're using VB.NET since you don't include a semicolon, didn't escape the backslash and due to the casing of the replace method used.

Ahmad Mageed
This is the correct answer
SLaks
You are the man... Although, there was no need to escape the backslash. simply Replace("\","/")
cinqoTimo
@cinqoTimo if you're using VB.NET there's no need to escape it, unlike C#. I'll update to reflect this.
Ahmad Mageed