在c#应用程序中通过蓝牙发送文件

时间:2013-05-15 13:24:54

标签: c# networking bluetooth

我想自动检测电脑周围的所有设备并向他们发送文件

我使用brecham和inhehand dll' s,

这是我的代码:

        BluetoothClient bc = new BluetoothClient();
        BluetoothDeviceInfo[] info = null;
        info = bc.DiscoverDevices(999);
        foreach (BluetoothDeviceInfo device in info)
        {
            lstDevices.Items.Add(device.DeviceName + device.DeviceAddress);
            device.Update();
            device.Refresh();
            device.SetServiceState(BluetoothService.ObexObjectPush, true);

            if (!device.Authenticated)
            {
                // Use pin "0000" for authentication
                if (!BluetoothSecurity.PairRequest(device.DeviceAddress, "0000")){
                    MessageBox.Show("Request failed");
                }

            }

            var file = @"C:\1.jpg";
            var uri = new Uri("obex://" + info[1].DeviceAddress + "/" + file);
            var request = new ObexWebRequest(uri);
            request.ReadFile(file);
            var response = (ObexWebResponse)request.GetResponse();
            MessageBox.Show(response.StatusCode.ToString());
            //check response.StatusCode
            response.Close();
        }

但我收到消息"请求失败!" 请有人纠正我吗?

有人有想法吗?

1 个答案:

答案 0 :(得分:3)

通过代码中的一点变化来解决问题:

        if (!BluetoothRadio.IsSupported)
            MessageBox.Show("No Bluetooth device detected.");
        if (BluetoothRadio.PrimaryRadio.Mode == RadioMode.PowerOff)
            BluetoothRadio.PrimaryRadio.Mode = RadioMode.Connectable;
        MessageBox.Show(BluetoothRadio.PrimaryRadio.Name.ToString());
        MessageBox.Show(BluetoothRadio.PrimaryRadio.Mode.ToString());
        BluetoothClient bc = new BluetoothClient();
        BluetoothDeviceInfo[] info = null;
        info = bc.DiscoverDevices(999);
        foreach (BluetoothDeviceInfo device in info)
        {
            lstDevices.Items.Add(device.DeviceName + " - " + device.DeviceAddress);
            device.Update();
            device.Refresh();
            device.SetServiceState(BluetoothService.ObexObjectPush, true);
            if (!device.Authenticated){
                // Use pin "0000" for authentication
                if (!BluetoothSecurity.PairRequest(device.DeviceAddress, "0000")){
                    MessageBox.Show("Request failed");
                }
            }
            var file = @"d:\1.jpg";
            var uri = new Uri("obex://" + device.DeviceAddress + "/" + file);
            var request = new ObexWebRequest(uri);
            request.ReadFile(file);
            var response = (ObexWebResponse)request.GetResponse();
            MessageBox.Show(response.StatusCode.ToString());
            // check response.StatusCode
            response.Close();
        }

希望它对你和每个需要它的人都有用:)