Share via


C# String Replace() not working?

Question

Thursday, January 10, 2008 9:00 PM

I've been trying to use the string.Replace() method to basically swap 2 folder locations, in other words i've passed an array of foldernames in a directory to a method, and using the string.replace method i'm trying to strip the original location of the folders in that directory off the string and replace it with another folder location so i can compare the 2 directory trees, for some reason i cant tell, it doesnt seem to work.  I've attached a screenshot whilst runnin in debug mode to show what the strings are and it should make more sense,  as in ChechForFoler string should be the same as targetRootFolder string once the replace method has done it's work but it isn't.

Screenshot:  here.

Any help would be appreciated.

Dave

All replies (3)

Thursday, January 10, 2008 9:16 PM âś…Answered | 4 votes

I was brave enough

String objects, once defined, never change.  When you call .Replace it actually returns a new string with the changes, and leaves the original untouched.

In practice the code often looks like myString = myString.Replace(something, something); .

-Ryan / Kardax


Thursday, January 10, 2008 9:13 PM

Post a code sample.  While your question may be sincere, I'm not clicking on that link.  I doubt if there are many other people brave enough to do so either.


Tuesday, December 20, 2011 10:00 AM

Strings are immutable in the .Net framework so therefore the cannot be edited. They have to be replaced by another string. The only way to build a string without creating a new string is using the stringBuilder class.