I've created a USB Device Scanner which allows the user to see all Devices in a Tree-Hierarchy. First i was happy that it worked, but after the joy I saw that my code quality was... not good (see code example).
For Better understanding: This is how the tree looks like and what the code is giving back.
BUS-Type Device Description
---------- -------------------
----------
PCI | |USB-Controller
USB | |----|USB-Root Hub
USB | |----|-----|Generic USB Hub
USB | |----|-----|-----|USB Device
USB | |----|-----|Generic USB Hub
. .
. .
And so on.
Now a code example:
if (hierarchyDeviceZero.Children.Count != 0) {
for (int usbHierarchyLevelOne = 0; usbHierarchyLevelOne < hierarchyDeviceZero.Children.Count; usbHierarchyLevelOne++) {
foreach (var hierarchyDeviceOne in usbDeviceTree.USBDeviceNodes.Where(
d1 => d1.HardwareID.Equals(hierarchyDeviceZero.Children[usbHierarchyLevelOne].HardwareID))
) {
Console.WriteLine("{0}\t|\t\t|---|{1}", hierarchyDeviceOne.EnumeratorName, hierarchyDeviceOne.Description);
if (hierarchyDeviceOne.Children.Count != 0) {
for (int usbHierarchyLevelTwo = 0; usbHierarchyLevelTwo < hierarchyDeviceZero.Children.Count; usbHierarchyLevelTwo++) {
foreach (var hierarchyDeviceTwo in usbDeviceTree.USBDeviceNodes.Where(
d1 => d1.HardwareID.Equals(hierarchyDeviceOne.Children[usbHierarchyLevelTwo].HardwareID))
) {
Console.WriteLine("{0}\t|\t\t |---|{1}", hierarchyDeviceTwo.EnumeratorName, hierarchyDeviceTwo.Description);
if (hierarchyDeviceTwo.Children.Count != 0) {
for (int usbHierarchyLevelThree = 0; usbHierarchyLevelThree < hierarchyDeviceZero.Children.Count; usbHierarchyLevelThree++) {
foreach (var hierarchyDeviceThree in usbDeviceTree.USBDeviceNodes.Where(
d1 => d1.HardwareID.Equals(hierarchyDeviceTwo.Children[usbHierarchyLevelThree].HardwareID))
) {
.
.
.
.
And so on (until 10th Hierarchylevel).
My Question is, how can i put this into a Recursive Method? I tried some tutorials but i somewhat did not understand how a method can call itself 10 times without overwriting its values... I hope you guys understand what i was trying to so.
PS.: Sorry for my bad english.
level