C# string replace does not actually replace the value in the string
The problem is that strings are immutable. The methods replace, substring, etc. do not change the string itself. They create a new string and replace it. So for the above code to be correct, it should be
path1 = path.Replace("\\bin\\Debug", "\\Resource\\People\\VisitingFaculty.txt");
Or just
path = path.Replace("\\bin\\Debug", "\\Resource\\People\\VisitingFaculty.txt");
if another variable is not needed.
This answer is also a reminder that strings are immutable. Any change you make to them will in fact create a new string. So keep that in mind with everything that involves strings, including memory management.
As stated in the documentation here.
String objects are immutable: they cannot be changed after they have
been created. All of the String methods and C# operators that appear
to modify a string actually return the results in a new string object
string.Replace (or other string modification) not working
Strings are immutable. The result of string.Replace
is a new string with the replaced value.
You can either store result in new variable:
var newString = someTestString.Replace(someID.ToString(), sessionID);
or just reassign to original variable if you just want observe "string updated" behavior:
someTestString = someTestString.Replace(someID.ToString(), sessionID);
Note that this applies to all other string
functions like Remove
, Insert
, trim and substring variants - all of them return new string as original string can't be modified.
Replace method is not replacing characters in a string
Just replace this line:
keyEdit.Replace('j', 'i');
with this:
keyEdit=keyEdit.Replace('j', 'i');
Returns a new string in which all occurrences of a specified string in
the current instance are replaced with another specified string. MSDN
String.Replace() doesn't work with |
You aren't putting the result back into connectionString
Try
connectionString = Properties.Settings.Default.KDatabaseConnectionString;
connectionString = connectionString.Replace(@"|DataDirectory|", Application.StartupPath);
Related Topics
How to Do a Deep Copy of an Object in .Net
Understanding Garbage Collection in .Net
Pre & Post Increment Operator Behavior in C, C++, Java, & C#
Possible to Call C++ Code from C#
How to Call Asynchronous Method from Synchronous Method in C#
What Is the Correct Way to Create a Single-Instance Wpf Application
Deserialize Json into C# Dynamic Object
Post a Form Array Without Successful
How to Strip HTML Tags from a String in Asp.Net
Case Insensitive 'Contains(String)'
How and When to Use 'Async' and 'Await'
C# Json.Net Convention That Follows Ruby Property Naming Conventions
C# Lambda Expressions: Why Should I Use Them