guiomie
guiomie

Reputation: 5148

String.format has no effect

The code executes without any error, but the {0} and {1} aren't replaced by the values declared in the String.Format

FileStream fs = new FileStream(xmlFile.FullName, FileMode.Open, FileAccess.Read);
XmlDocument doc = new XmlDocument();
doc.Load(fs);

 string docStrXml = doc.InnerXml.ToString();
 String.Format(docStrXml, newVersion.ToString(), oldVersion.ToString());

 triggerDocument.LoadXml(docStrXml);
 triggerDocument.Save(directoryPathOfNewXml + "\\" + xmlFile.Name);

The new file is saved without a problem. Basically, I'm opening an xml file, and I want to insert strings in the document. Here is the initial document (and also the last since it doesn't change):

<?xml version="1.0" encoding="utf-8" ?>
<Package
    source="http://localhost/Service/Master/{0}/{1}/"
    triggerseturl="http://localhost/Service/Master/{0}/{1}/client.xml">
  <File name="client_full.xml"/>
  <File name="client_half.xml"/>
</Package>

Upvotes: 1

Views: 149

Answers (3)

Michael
Michael

Reputation: 1833

The String.Format method returns a string based on the string argument passed [docStrXml], but doesn't operate directly on it. You'll need to assign the return value to a variable, in this case the same one you pass to the method. Modify your code to this:

docStrXml = String.Format(docStrXml, newVersion.ToString(), oldVersion.ToString());

and you should be good to go.

Upvotes: 1

TWA
TWA

Reputation: 12816

Strings are immutable, you must assign the return value of string.Format to another variable.

It will have the new string with the inserted values.

docStrXml = String.Format(docStrXml, newVersion.ToString(), oldVersion.ToString());

Upvotes: 3

horgh
horgh

Reputation: 18543

You forgot to replace the value in docStrXml with the new value:

docStrXml = String.Format(docStrXml, newVersion.ToString(), oldVersion.ToString());

Upvotes: 3

Related Questions