1

i have a controller where i read a html file into a variable.

After read it i replace some values from the variable to other values,

but the problem is that nothing happend.

What is wrong here ?

can someone give me a hand with this?

string path = "/mypath/myfile.html";
string s = System.IO.File.ReadAllText(path);
s.Replace("@%a%@","hi");
s.Replace("@%b%@","yo");
s.Replace("@%c%@","asdfasdf");
s.Replace("@%d%@", "http://www.google.com");
1
  • 4
    string in .NET is immutable Commented Nov 21, 2013 at 16:28

2 Answers 2

4

Strings are immutable - you should assign result of replacement to your string. Also you can chain replacement operations like this:

string s = System.IO.File.ReadAllText(path)
             .Replace("@%a%@","hi")
             .Replace("@%b%@","yo")
             .Replace("@%c%@","asdfasdf")
             .Replace("@%d%@", "http://www.google.com");

Just keep in mind - all string operations (like Replace, Substring etc) will create and return new string, instead of changing original. Same implies to operations on DateTime and other immutable objects.

UPDATE: You can also declare dictionary of your replacements and update string in a loop:

 var replacements = new Dictionary<string, string> {
     { "@%a%@","hi" }, { "@%b%@","yo" }, { "@%c%@","asdfasdf" } // ...
 };

 string s = System.IO.File.ReadAllText(path);

 foreach(var replacement in replacements)
    s = s.Replace(replacement.Key, repalcement.Value);
Sign up to request clarification or add additional context in comments.

Comments

2

A string is immutable. Basically, an object is immutable if its state doesn’t change once the object has been created. Consequently, a class is immutable if its instances are immutable.

string path = "/mypath/myfile.html";
string s = System.IO.File.ReadAllText(path);
s = s.Replace("@%a%@","hi");
s = s.Replace("@%b%@","yo");
s = s.Replace("@%c%@","asdfasdf");
s = s.Replace("@%d%@", "http://www.google.com");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.