`
hzy3774
  • 浏览: 985136 次
  • 性别: Icon_minigender_1
  • 来自: 珠海
社区版块
存档分类
最新评论

C#编程连接蓝牙设备,文件收发

 
阅读更多

现在很多电脑提供了蓝牙支持,很多笔记本网卡也集成了蓝牙功能,也可以采用USB蓝牙方便的连接手机等蓝牙设备进行通信。

操作蓝牙要使用类库InTheHand.Net.Personal

首先在项目中引用该类库;

static void Main(string[] args)
{
    BluetoothRadio bluetoothRadio = BluetoothRadio.PrimaryRadio;
    if (bluetoothRadio == null)
    {
	Console.WriteLine("没有找到本机蓝牙设备!");
    }
    else
    {
	Console.WriteLine("ClassOfDevice: " + bluetoothRadio.ClassOfDevice);
	Console.WriteLine("HardwareStatus: " + bluetoothRadio.HardwareStatus);
	Console.WriteLine("HciRevision: " + bluetoothRadio.HciRevision);
	Console.WriteLine("HciVersion: " + bluetoothRadio.HciVersion);
	Console.WriteLine("LmpSubversion: " + bluetoothRadio.LmpSubversion);
	Console.WriteLine("LmpVersion: " + bluetoothRadio.LmpVersion);
	Console.WriteLine("LocalAddress: " + bluetoothRadio.LocalAddress);
	Console.WriteLine("Manufacturer: " + bluetoothRadio.Manufacturer);
	Console.WriteLine("Mode: " + bluetoothRadio.Mode);
	Console.WriteLine("Name: " + bluetoothRadio.Name);
	Console.WriteLine("Remote:" + bluetoothRadio.Remote);
	Console.WriteLine("SoftwareManufacturer: " + bluetoothRadio.SoftwareManufacturer);
	Console.WriteLine("StackFactory: " + bluetoothRadio.StackFactory);
    }
    Console.ReadKey();
}

 如果PC插入了蓝牙适配器,便会显示蓝牙相关信息:


 

然后我们就要利用蓝牙收发文件了:

前提是蓝牙设备(如手机)已经和PC配对了

    public partial class Form1 : Form
    {
        BluetoothRadio radio = null;//蓝牙适配器
        string sendFileName = null;//发送文件名
        BluetoothAddress sendAddress = null;//发送目的地址
        ObexListener listener = null;//监听器
        string recDir = null;//接受文件存放目录
        Thread listenThread, sendThread;//发送/接收线程

        public Form1()
        {
            InitializeComponent();
            radio = BluetoothRadio.PrimaryRadio;//获取当前PC的蓝牙适配器
            CheckForIllegalCrossThreadCalls = false;//不检查跨线程调用
            if (radio == null)//检查该电脑蓝牙是否可用
            {
                MessageBox.Show("这个电脑蓝牙不可用!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            recDir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            labelRecDir.Text = recDir;
        }

        private void buttonSelectBluetooth_Click(object sender, EventArgs e)//选择远程蓝牙设备
        {
            SelectBluetoothDeviceDialog dialog = new SelectBluetoothDeviceDialog();
            dialog.ShowRemembered = true;//显示已经记住的蓝牙设备
            dialog.ShowAuthenticated = true;//显示认证过的蓝牙设备
            dialog.ShowUnknown = true;//显示位置蓝牙设备
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                sendAddress = dialog.SelectedDevice.DeviceAddress;//获取选择的远程蓝牙地址
                labelAddress.Text = "地址:" + sendAddress.ToString() + "    设备名:" + dialog.SelectedDevice.DeviceName;
            }
        }

        private void buttonSelectFile_Click(object sender, EventArgs e)//选择要发送的本地文件
        {
            OpenFileDialog dialog = new OpenFileDialog();
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                sendFileName = dialog.FileName;//设置文件名
                labelPath.Text = Path.GetFileName(sendFileName);
            }
        }

        private void buttonSend_Click(object sender, EventArgs e)//发送按钮
        {
            sendThread = new Thread(sendFile);//开启发送文件线程
            sendThread.Start();
        }

        private void sendFile()//发送文件方法
        {
            ObexWebRequest request = new ObexWebRequest(sendAddress, Path.GetFileName(sendFileName));//创建网络请求
            WebResponse response = null;
            try
            {
                buttonSend.Enabled = false;
                request.ReadFile(sendFileName);//发送文件
                labelInfo.Text = "开始发送!";
                response = request.GetResponse();//获取回应
                labelInfo.Text = "发送完成!";
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("发送失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                labelInfo.Text = "发送失败!";
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    buttonSend.Enabled = true;
                }
            }
        }

        private void buttonselectRecDir_Click(object sender, EventArgs e)//选择接受目录
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择蓝牙接收文件的存放路径";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                recDir = dialog.SelectedPath;
                labelRecDir.Text = recDir;
            }
        }

        private void buttonListen_Click(object sender, EventArgs e)//开始/停止监听
        {
            if (listener == null || !listener.IsListening)
            {
                radio.Mode = RadioMode.Discoverable;//设置本地蓝牙可被检测
                listener = new ObexListener(ObexTransport.Bluetooth);//创建监听
                listener.Start();
                if (listener.IsListening)
                {
                    buttonListen.Text = "停止";
                    labelRecInfo.Text = "开始监听";
                    listenThread = new Thread(receiveFile);//开启监听线程
                    listenThread.Start();
                }
            }
            else
            { 
                listener.Stop();
                buttonListen.Text = "监听";
                labelRecInfo.Text = "停止监听";
            }
        }

        private void receiveFile()//收文件方法
        {
            ObexListenerContext context = null;
            ObexListenerRequest request = null;
            while (listener.IsListening)
            {
                context = listener.GetContext();//获取监听上下文
                if (context == null)
                {
                    break;
                }
                request = context.Request;//获取请求
                string uriString = Uri.UnescapeDataString(request.RawUrl);//将uri转换成字符串
                string recFileName = recDir + uriString;
                request.WriteFile(recFileName);//接收文件
                labelRecInfo.Text = "收到文件" + uriString.TrimStart(new char[] { '/' });
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (sendThread != null)
            {
                sendThread.Abort();
            }
            if (listenThread != null)
            {
                listenThread.Abort();
            }
            if (listener != null && listener.IsListening)
            {
                listener.Stop();
            }
        }
    }

程序界面:

 

 

 

 SelectBluetoothDeviceDialog是一个InTheHand.Net.Personal提供的窗体,用于选择蓝牙设备:



 从手机往电脑发送文件需要在电脑上开启监听ObexListener,才能收到文件。



 核心代码:

 

BluetoothRadio radio = null;//蓝牙适配器
string sendFileName = null;//发送文件名
BluetoothAddress sendAddress = null;//发送目的地址
ObexListener listener = null;//监听器
string recDir = null;//接受文件存放目录
Thread listenThread, sendThread;//发送/接收线程

radio = BluetoothRadio.PrimaryRadio;//获取当前PC的蓝牙适配器

//关于蓝牙设备选择对话框
SelectBluetoothDeviceDialog dialog = new SelectBluetoothDeviceDialog();
dialog.ShowRemembered = true;//显示已经记住的蓝牙设备
dialog.ShowAuthenticated = true;//显示认证过的蓝牙设备
dialog.ShowUnknown = true;//显示位置蓝牙设备
sendAddress = dialog.SelectedDevice.DeviceAddress;//获取选择的远程蓝牙地址

//发送文件操作
ObexWebRequest request = new ObexWebRequest(sendAddress, Path.GetFileName(sendFileName));//创建网络请求
WebResponse response = null;
request.ReadFile(sendFileName);//发送文件
response = request.GetResponse();//获取回应
response.Close();

//接收文件
radio.Mode = RadioMode.Discoverable;//设置本地蓝牙可被检测
listener = new ObexListener(ObexTransport.Bluetooth);//创建监听
listener.Start();
listener.Stop();

ObexListenerContext context = null;
ObexListenerRequest request = null;
context = listener.GetContext();//获取监听上下文
request = context.Request;//获取请求
string uriString = Uri.UnescapeDataString(request.RawUrl);//将uri转换成字符串
string recFileName = recDir + uriString;
request.WriteFile(recFileName);//接收文件
labelRecInfo.Text = "收到文件" + uriString.TrimStart(new char[] { '/' }

 

end

  • 大小: 34.1 KB
  • 大小: 35.2 KB
  • 大小: 24.3 KB
  • 大小: 25 KB
分享到:
评论
5 楼 熊猫仙 2018-08-10  
请问,这个程序可以和BLE蓝牙设备通讯吗?
4 楼 lsy234009 2017-05-07  
“这个电脑蓝牙不可用!”原因多半是你没打开蓝牙
3 楼 lixiang2202 2016-04-10  
你好,我想请教一个问题,在使用InTheHand库开发蓝牙文件接收的时候,手机选择多个文件,通过蓝牙发送,程序只能收到一个文件,而手机端同样显示第一个文件成功,其他文件失败。请问对于多文件接收,您有什么这方面的经验?谢谢
2 楼 昂望星空 2015-11-01  
q2108907 写道
为什么,我的电脑插上蓝牙执行后,直接提示 “这个电脑蓝牙不可用!”

我的也是这种情况,是用CSR蓝牙
1 楼 q2108907 2015-02-01  
为什么,我的电脑插上蓝牙执行后,直接提示 “这个电脑蓝牙不可用!”

相关推荐

    C#代码连接蓝牙设备

    c#代码编写连接 PC 蓝牙连接到苹果手机的蓝牙,测试连接可行,网上很多代码,很混乱,不好连接!

    C# 蓝牙配对连接发送及接收文件源代码全(测试通过)

    C#利用开源控件InTheHand.Net.Personal.dll制作的完整配对,发送及接收文件,可以连接手机也可以连接电脑。

    C#代码连接蓝牙设备.zip

    c#代码编写连接 PC 蓝牙连接到苹果手机的蓝牙,测试连接可行,网上很多代码,很混乱,不好连接!

    windows BLE编程 net winform 连接蓝牙低功耗

    winform 程序调用Windows.Devices.Bluetoot API 实现windows下BLE蓝牙设备自动连接,收发数据功能。不需要使用win10的UWP开发。 实际例子用vs2022编写,可直接编译运行

    C#扫描蓝牙设备demo

    C#扫描蓝牙设备demo 直接运行就可使用 含dll及代码 绝对可用!!! C#扫描蓝牙设备demo 直接运行就可使用 含dll及代码 绝对可用!!!

    C#编程 文件操作 FileCopyPlan(源码)(源码)

    C#编程 文件操作 FileCopyPlan(源码)(源码)C#编程 文件操作 FileCopyPlan(源码)(源码)C#编程 文件操作 FileCopyPlan(源码)(源码)C#编程 文件操作 FileCopyPlan(源码)(源码)C#编程 文件操作 FileCopyPlan(源码)(源码)...

    C#编程 文件操作 GetShortPathName(源码)(源码)

    C#编程 文件操作 GetShortPathName(源码)(源码)C#编程 文件操作 GetShortPathName(源码)(源码)C#编程 文件操作 GetShortPathName(源码)(源码)C#编程 文件操作 GetShortPathName(源码)(源码)C#编程 文件操作 ...

    C#编程 文件操作 AllowDropFile(源码)(源码)

    C#编程 文件操作 AllowDropFile(源码)(源码)C#编程 文件操作 AllowDropFile(源码)(源码)C#编程 文件操作 AllowDropFile(源码)(源码)C#编程 文件操作 AllowDropFile(源码)(源码)C#编程 文件操作 AllowDropFile(源码)...

    C#编程 文件操作 WordReplace(源码)(源码)

    C#编程 文件操作 WordReplace(源码)(源码)C#编程 文件操作 WordReplace(源码)(源码)C#编程 文件操作 WordReplace(源码)(源码)C#编程 文件操作 WordReplace(源码)(源码)C#编程 文件操作 WordReplace(源码)(源码)C#...

    C#编程 文件操作 CreateFile(源码)(源码)

    C#编程 文件操作 CreateFile(源码)(源码)C#编程 文件操作 CreateFile(源码)(源码)C#编程 文件操作 CreateFile(源码)(源码)C#编程 文件操作 CreateFile(源码)(源码)C#编程 文件操作 CreateFile(源码)(源码)C#编程 ...

    C#编程 文件操作 ReadFileByLine(源码)(源码)

    C#编程 文件操作 ReadFileByLine(源码)(源码)C#编程 文件操作 ReadFileByLine(源码)(源码)C#编程 文件操作 ReadFileByLine(源码)(源码)C#编程 文件操作 ReadFileByLine(源码)(源码)C#编程 文件操作 ReadFileByLine...

    C#编程 文件操作 INIFileOperate(源码)(源码)

    C#编程 文件操作 INIFileOperate(源码)(源码)C#编程 文件操作 INIFileOperate(源码)(源码)C#编程 文件操作 INIFileOperate(源码)(源码)C#编程 文件操作 INIFileOperate(源码)(源码)C#编程 文件操作 INIFileOperate...

    C#编程 文件操作 MultiFormatTxt(源码)(源码)

    C#编程 文件操作 MultiFormatTxt(源码)(源码)C#编程 文件操作 MultiFormatTxt(源码)(源码)C#编程 文件操作 MultiFormatTxt(源码)(源码)C#编程 文件操作 MultiFormatTxt(源码)(源码)C#编程 文件操作 MultiFormatTxt...

    C# 蓝牙 文件传输 DEMO

    C# 蓝牙 文件传输 完整 DEMO

    C#编程如何从文件中读取文件内容

    C#编程如何从文件中读取文件内容C#编程如何从文件中读取文件内容C#编程如何从文件中读取文件内容C#编程如何从文件中读取文件内容C#编程如何从文件中读取文件内容

    C#编程 文件操作 RansackFile(源码)(源码)

    C#编程 文件操作 RansackFile(源码)(源码)C#编程 文件操作 RansackFile(源码)(源码)C#编程 文件操作 RansackFile(源码)(源码)C#编程 文件操作 RansackFile(源码)(源码)C#编程 文件操作 RansackFile(源码)(源码)C#...

    C#编程 文件操作 ClearRecycle(源码)(源码)

    C#编程 文件操作 ClearRecycle(源码)(源码)C#编程 文件操作 ClearRecycle(源码)(源码)C#编程 文件操作 ClearRecycle(源码)(源码)C#编程 文件操作 ClearRecycle(源码)(源码)C#编程 文件操作 ClearRecycle(源码)(源码)...

    C#编程 文件操作 DeleteDirByDG(源码)(源码)

    C#编程 文件操作 DeleteDirByDG(源码)(源码)C#编程 文件操作 DeleteDirByDG(源码)(源码)C#编程 文件操作 DeleteDirByDG(源码)(源码)C#编程 文件操作 DeleteDirByDG(源码)(源码)C#编程 文件操作 DeleteDirByDG(源码)...

    C#编程 文件操作 WordToHTML(源码)(源码)

    C#编程 文件操作 WordToHTML(源码)(源码)C#编程 文件操作 WordToHTML(源码)(源码)C#编程 文件操作 WordToHTML(源码)(源码)C#编程 文件操作 WordToHTML(源码)(源码)C#编程 文件操作 WordToHTML(源码)(源码)C#编程 ...

Global site tag (gtag.js) - Google Analytics