tags:

views:

196

answers:

6

I have a string which I read in from :

TextReader tr = new StreamReader(this.dataPath );
string contents = tr.ReadToEnd();

The value of contents begins with:

"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n....."

When I try execute

        string styleSheet = "<?xml-stylesheet type=\"text/xsl\" href=\"message.xsl\"?>";
        string xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
        TextReader tr = new StreamReader(this.dataPath );
        string contents = tr.ReadToEnd(); 
        contents.Replace(xmlString,xmlString + styleSheet );

It absolutely won't find the first occurance of XmlString. Any ideas why?

+25  A: 

Try

contents = contents.Replace(xmlString,xmlString + styleSheet );

This is because the String class is immutable.

Joe
+1 - A classic, the effect of the immutable string class
Fredrik Mörk
I used to do that all of the time.
Ed Swangren
@Ed I still do it from time to time :)
Rex M
hehe, it sure got me good :)
JL
This is the type of thing you fail interviews over....
JL
+2  A: 

you probably want to do this:

string styleSheet = "<?xml-stylesheet type=\"text/xsl\" href=\"message.xsl\"?>";
string xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
TextReader tr = new StreamReader(this.dataPath );
string contents = tr.ReadToEnd(); 
string result = contents.Replace(xmlString,xmlString + styleSheet );

You're currently not capturing the replace results that you're doing on the last line.

Joseph
+4  A: 

The Replace() method returns a new string object, so you'll have to change your code to:

 content = contents.Replace(xmlString,xmlString + styleSheet );
Philippe Leybaert
+1  A: 

System.String is immutable. Operations such as Replace return a new string rather than modifying this string. Use System.Text.StringBuilder if you truly need a mutable string or just assign the result of the Replace call to a variable.

Brian Ensink
+1  A: 

To get technical (and who doesn't love that), if you are searching for the string`

<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n.....

The search string would have to be

"<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\"?>\\r\\n"

or

 @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"
jenningj
+1  A: 

This doesn't really answer your question but that has already been answered more than once so please permit me this aside.

I've seen many cases where people read the content of a stream into a string so that some really simple manipulation can be done. In many cases and certainly this case the operation can be performed without ever making a copy of the whole string and working on that.

With a little more effort than your existing code you could write a StreamStringReplace method that takes as its parameters an input stream, an output stream, a find string and a replace string. This would be much more efficient especially if your xml docs can get massive.

Chris Simpson