Copying Files

The TransferFiles method first sets both LEDs to blink green and then starts the actual copying process, which takes place in the DeepCopy method shown in the following code. After the deep copy has completed then both LEDs will be set to green again to indicate a successful copy.

The call to DeepCopy is contained within a try catch block. This ensures that if anything goes wrong inside the try block, the code in the catch block will be run. This will set both LEDs to flash red.

Try/Catch blocks are a useful mechanism for handling situations where things can go wrong. Not more so than in a situation where the program code is dependent on real hardware. For instance, unplugging the USB flash drive while copying is in progress:

private void TransferFiles()
{
    ledSD.BlinkRepeatedly(Colors.Green);
    ledUSB.BlinkRepeatedly(Colors.Green);
    try
    {
        CopyFiles("\\");
        DeepCopy(sdStorageDevice.ListRootDirectorySubdirectories());
        ledSD.TurnOff();
        ledSD.TurnGreen();
        ledUSB.TurnOff();
        ledUSB.TurnGreen();
    }
    catch (Exception)
    {
        ledSD.BlinkRepeatedly(Colors.Red);
        ledUSB.BlinkRepeatedly(Colors.Red);
    }
}

One of the problems of copying the files from an SD card that is used in a camera is that the image files are always contained in a folder, or even in a folder inside another folder. So, to be sure of finding every image file on the SD card, we need to check every folder at the top level of the SD card, copy all of the files in that folder and if that folder contains a folder, check that folder ...

Get Getting Started with .NET Gadgeteer now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.