Search code examples
bluetoothwindows-10uwpbackground-task

FromBluetoothAddressAsync throws 'System.IO.FileNotFoundException' in mscorlib.ni.dll


I'm developing an app that connects ta a BLE beacon, for this I use the BluetoothLEAdvertisementWatcher API. When I receive an advertisement I want to connect to the device to read the GATT characteristics.

So I start a BLEwatcher

    BluetoothLEAdvertisementWatcher watcher;
    watcher.Received += OnAdvertisementReceived;
    watcher.Stopped += OnAdvertisementWatcherStopped;
    watcher.Start();

Then I try to access the device

private async void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs)
{
    var address = eventArgs.BluetoothAddress;

    BluetoothLEDevice device = await BluetoothLEDevice.FromBluetoothAddressAsync(eventArgs.BluetoothAddress);
    Debug.WriteLine(device.Name + " - " + device.DeviceId);
    ....

This fails with (at FromBluetoothAddressAsync line)

An exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.ni.dll but was not handled in user code

Additional information: The system cannot find the file specified. (Exception from HRESULT: 0x80070002)

The funny thing is: if I open the system's bluetooth devices window it works fine!

So when I open the bluetooth devices window and run the app the error is not thrown, when I close the bluetooth devices window it throws the error.

Note that it always throws this error in a background task.

Apparently it does work on build 10.0.10586.218. I found this online from someone with the same issue:

LUMIA 950, Windows 10, 1511, 10.0.14332.1001

Exception thrown on FromIdAsync(): 'System.IO.FileNotFoundException' in mscorlib.ni.dll

LUMIA 730, Windows 10, 1511, 10.0.10586.218

Exception thrown on FindAllAsync(): 'System.ArgumentException'

LUMIA 920, Windows 10, 1511, 10.0.10586.218

No Error!

Screenshots: When it fails

When it works


Solution

  • Aren't the BLE Windows APIs lovely and the nice (un)documented exceptions they give you?

    You shouldn't use AdvertisementWatcher if you have the intent to pair to a device I guess. Instead use a DeviceInformation watcher with a specific selector for BLE-devices that contain both paired and non-paired devices. That will give a ready-to-use DeviceInformation object you can pair with.

    The sample code for that can be seen at https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/DeviceEnumerationAndPairing, scenario number 8.