I can only use the .NET 2.0 framework to create an XML document (> 1000 lines).
The information for the document is retrieved from the Windows Registry. The XML is written using 2 for loops and in these loops I call 3 the .ToString() method to convert the retrieved data.
As expected, it takes ages to create the XML document. I was wondering what can I do to optimize this.
public static void InitiateApp()
{
const string regadd = "SOFTWARE" + "\\" + "\\" + "Microsoft" + "\\" + "Windows NT" + "\\" + "CurrentVersion" + "\\Fonts";
RegistryKey regkey = Registry.LocalMachine.OpenSubKey(regadd);
XmlWriterSettings settings = new XmlWriterSettings();
settings.CloseOutput = true;
settings.Indent = true;
settings.IndentChars = "\t";
settings.NewLineChars = "\r\n";
settings.NewLineOnAttributes = true;
settings.OmitXmlDeclaration = true;
XmlWriter w = XmlWriter.Create("c:\\out.xml",settings);
foreach (FontFamily font in FontFamily.Families)
{
w.WriteStartElement("FontFamily");
int keyCount = 0;
foreach (string key in regkey.GetValueNames())
{
if(regkey.GetValueNames()[keyCount].ToString().Contains(font.Name))
{
w.WriteStartElement("FontName",regkey.GetValueNames()[keyCount].ToString());
w.WriteElementString("FontFile",regkey.GetValue(key).ToString());
w.WriteEndElement();
}
keyCount++;
}
w.WriteEndElement();
}
w.Flush();
}
Separate the registry access from the xml writing. Then you can measure each and see which is slow.
GetValueNames returns a string[], why call ToString?
Why call GetValueNames so much?