Writing to SD Card exception

Hi all,

My code gives error when i connect my keyboard as “An unhandled exception of type ‘System.InvalidOperationException’ occurred in GHIElectronics.NETMF.IO.dll” :

Thanks for advance :


static USBH_Keyboard keyboard;
    static string okunan = "";
    static OutputPort red, yellow, green;
    static PersistentStorage sdPS;

    public static void Main()
    {
        // ... check if SD is inserted

        // SD Card is inserted
        // Create a new storage device
        sdPS = new PersistentStorage("SD");
        // Mount the file system
        sdPS.MountFileSystem();
        // Assume one storage device is available,
        // access it through NETMF
        string rootDirectory = VolumeInfo.GetVolumes()[0].RootDirectory;
        FileStream FileHandle = new FileStream(rootDirectory + @ "\log.txt", FileMode.Append );
        byte[] data =
        Encoding.UTF8.GetBytes("Program başlatılıyor : " + System.DateTime.Now );
        // write the data and close the file
        FileHandle.Write(data, 0, data.Length);
        


        data =
        Encoding.UTF8.GetBytes("IP alınıyor : " + System.DateTime.Now);
        // write the data and close the file
        FileHandle.Write(data, 0, data.Length);
        
        red = new OutputPort((Cpu.Pin)FEZ_Pin.Digital.Di3, false);
        green = new OutputPort((Cpu.Pin)FEZ_Pin.Digital.Di2, false);
        yellow = new OutputPort((Cpu.Pin)FEZ_Pin.Digital.Di8, false);
        //PWM piezo = new PWM((PWM.Pin)FEZ_Pin.PWM.Di5);
        
        // Subscribe to USBH event.
        USBHostController.DeviceConnectedEvent += DeviceConnectedEvent;
        USBHostController.DeviceDisconnectedEvent  += DeviceDisconnectedEvent;

        // Sleep forever
        Thread.Sleep(Timeout.Infinite);

    }

   static void DeviceConnectedEvent(USBH_Device device)
    {
        if (device.TYPE == USBH_DeviceType.Keyboard)
        {

            // ... check if SD is inserted

            // SD Card is inserted
            // Create a new storage device

 /* !******************GIVES ERROR HERE*************************! */

            sdPS = new PersistentStorage("SD");
            // Mount the file system
            sdPS.MountFileSystem();
            string rootDirectory = VolumeInfo.GetVolumes()[0].RootDirectory;

            FileStream FileHandle = new FileStream(rootDirectory + @ "\log.txt", FileMode.Append);
            byte[] data =
            Encoding.UTF8.GetBytes("Klavye bağlandı : " + System.DateTime.Now);
            // write the data and close the file
            FileHandle.Write(data, 0, data.Length);
        
            Debug.Print("Klavye Bağlandı");
            keyboard = new USBH_Keyboard(device);
            keyboard.KeyUp += Keyup;

            // Hazır halde, sarı yanıyor
            yellow.Write(true);
            green.Write(false);
            red.Write(false);
        }
    }


You have SD mounted in main and then second time inside your event handler.