One of the challenges of automatically preparing a wxs (which is in xml) file for WiX to process into an msi file for installation, was creating a recursive algorithm to read a target directory an get all sub-directories and corresponding files. The problem I was having, was that I could get all directories and files, but I couldn’t add them to the wxs file with the depth which they came out.
Finally, after much experimenting and searching around, I found a project by Damian Castroviejo, which was written in VB, but exactly what I was looking for. Here is my interpretation on it:
|public class loopDirectoryNodes
public void getDirNodes(XmlDocument xmlDoc, XmlElement xe, String path)
foreach (String dir in Directory.GetDirectories(path))
XmlElement dirChild = xmlDoc.CreateElement(“Directory”);
Console.WriteLine(“Adding Directory: ” + dir);
foreach (String fileName in Directory.GetFiles(dir, “*.*”))
XmlElement xeCom = xmlDoc.CreateElement(“Component”);
XmlElement xeFile = xmlDoc.CreateElement(“File”);
Console.WriteLine(“Adding File: ” + fileName);
getDirNodes(xmlDoc, dirChild, dir);
The parameters passed to the method getDirNodes, are the xmlDoc which is the XML document which the nodes will be added to, xe is the XML Element which is the node you want the directories to be added to, and path is the Directory which you wish you map the sub-directories and files.
The first foreach statement will loop through the Directory passed to find all sub-directories and add each of them to the xe XML Element passed in the parameter, while the second foreach will loop through each of those sub-directories found, and add the files within them to the sub-directory node being searched. Once all the file for the sub-directory are found (if any), the method calls itself, passing the same XML Document xmlDoc, but with the XML Element of the sub-directory just searched and it path, to search that sub-directory for any other directories within.
Once all sub-directories of a folder are found, the method returns to where it was called in itself, and continues on to the next directory, until all directories are found. Genius, thanks Damian, you helped me a lot!