Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace slashes in .Net

Tags:

.net

vb.net

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.

like image 361
tpow Avatar asked Dec 10 '22 17:12

tpow


2 Answers

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.

like image 68
Ahmad Mageed Avatar answered Dec 23 '22 08:12

Ahmad Mageed


\ 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('\\','/')
like image 37
AxelEckenberger Avatar answered Dec 23 '22 08:12

AxelEckenberger