c# - Error trying to Replace a string

Asked

Viewed 106 times

3

Boa Pessoal,

I have the following problem:

While trying to do the replace of a string (of a Literal Control), using the code below, the value of the code is not changed.

 MyControl.Text.Replace("id=\"KP\"", "id=\"KPC\"");

However, if I try to change only the value of the id (as shown in the following code), it works perfectly.

 MyControl.Text.Replace("KP", "KPC");

P.S: I have to use id in replace, because the text of literal contain more than once the reference to the value of the id.

[EDIT] - I leave an excerpt from literal for better understanding (is repetitive)

<li><a class="fancybox" title="BK-001" href="imgpeles/KP-01.jpg" rel="fancybox">
    <img alt="" src="imgpeles/KP-01_t.jpg" width="55" height="55" id="KP-01"><br>
    BK-001</a>
</li>
  • I created a small example and everything worked correctly, I do not understand why it is not working. Put the code like this, correct? MyControl.Text = MyControl.Text.Replace("id=\"KP\"", "id=\"KPC\"");

  • @Joãomartins exactly like this, I can’t see the error...

  • @Joãomartins made an edition and I put an excerpt from literal

  • 1

    I don’t think he’s "liking" the "" in the text. Try it like this: MyControl.Text.Replace(@"id=""KP""", @"id=""KPC""");

  • @Joãomartins I think I’ve tried all the possibilities except the one that will be the xD solution, I’ve tried this too and nothing (despite being a good proposal). I, too, have already come to the conclusion that "" will be the problem, but since I can’t remove it (since it corresponds to a path), I don’t know very well where to guide myself.

  • Possible duplicate of Replace com does not work

  • @ramaral does not think it is duplicated, because the code MyControl.Text.Replace(@"id=""KP""", @"id=""KPC"""); doesn’t work either. Something’s not right here...

  • @ramaral, I may be mistaken, but I think it is not duplicated, even because if I replace the bar by two, it will also replace those of the elements (a and li)

  • @Adrianomaia is sure that the text id=\"KP\" exists exactly this way in the MyControl.Text?

  • @Joãomartins yes, I also checked it in Debug

  • 2

    I understand you are trying to replace (id="KP-01"), but your code considers (id="KP"). I believe this may be the error.

  • @Filipeandréfloriani, not xD. I just want to replace the part KP for KPC

  • So take the last "

  • 1

    I will simulate here and if it goes well put as an answer

Show 9 more comments

1 answer

4


Follows below solution:

string teste = System.IO.File.ReadAllText("c:\\arquivo.txt");          

teste = teste.Replace("id=\"KP", "id=\"KPC");

Note: The file .txt contained your HTML.

  • 1

    that’s right. Thank you very much :).

  • 1

    I’m glad it’s settled! :]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.