I am sitting here finding myself writing a recursive call for C# to write a RegistryKey.
This is something I could hard code easily enough, but I'd to do it recursively.
using System;
using System.Collections.Generic;
using Microsoft.Win32;
private const string regKeyPath = @"Software\Apps\jp2code\net\TestApp";
static void Main() {
string[] split = regKeyPath.Split('\\');
RegistryKey key = null;
try {
keyMaker(Registry.LocalMachine, split);
} finally {
if (key != null) {
key.Close();
}
}
// continue on with Application.Run(new Form1());
}
So, keyMaker is what I want to be my recursive function.
private static void keyMaker(RegistryKey key, string[] path) {
string subKey = null;
string[] subKeyNames = key.GetSubKeyNames();
foreach (var item in subKeyNames) {
if (path[0] == item) {
subKey = item;
}
}
RegistryKey key2 = null;
try {
if (String.IsNullOrEmpty(subKey)) {
key2 = key.CreateSubKey(subKey);
} else {
key2 = key.OpenSubKey(subKey);
}
keyMaker(key2, &path[1]); // <= NOTE! Not allowed/defined in C#
} finally {
key2.Close();
}
}
So, I can't simply pass the array starting with the next element of the array.
Is there a neat way to do this in C#?
The Registry bit has nothing to do with the problem but to add my real world problem to an array task.
ArraySegmentthat you could use to pass the remainder of the path array (without allocating new arrays, and allows you to get back to the original)