C# 中的 32feet.NET 蓝牙监听器

问题描述 投票:0回答:1

我有一个版本为.net Framework 4.7.2的Windows应用程序,我需要一个蓝牙监听器来接收和保存通过蓝牙发送到该设备的文件。

我使用 32feet.NET,我编写了这段代码:

但是它有一些问题。如果推荐其他方式,请告诉我。否则请帮助我解决当前的问题。

  1. 当我读取流字节写入文件时花了很长时间。写入后,写入文件的数据是错误的:(

  2. 如何获得接收文件的扩展名?

public Form1()
{
    InitializeComponent();

    _bluetoothListener = new BluetoothListener(BluetoothService.ObexObjectPush);
    _listenerThread = new Thread(ListenForBluetoothRequests);
    _listenerThread.Start();
}

private void ListenForBluetoothRequests()
{
    _bluetoothListener.Start();

    while (true)
    {
        try
        {
            _bluetoothListener.Pending();
            BluetoothClient client = _bluetoothListener.AcceptBluetoothClient();

            if (client != null)
            {
                // Handle the incoming file transfer
                HandleIncomingFile(client);

                // Close the client connection
                client.Close();
            }
        }
        catch (IOException ex)
        {
            // Handle exceptions, if any
            Console.WriteLine("Exception: " + ex.Message);
        }
    }
}

private void HandleIncomingFile(BluetoothClient client)
{
    // Customize the file save path as per your requirement
    string savePath = "C:\\BluetoothReceivedFiles\\";

    if (!Directory.Exists(savePath))
    {
        Directory.CreateDirectory(savePath);
    }

    Stream networkStream = client.GetStream();
    byte[] buffer = new byte[1024];
    int bytesRead;

    // Read the incoming file and save it
    using (FileStream fileStream = File.Create(Path.Combine(savePath, "ReceivedFile.txt")))
    {
        while ((bytesRead = networkStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            fileStream.Write(buffer, 0, bytesRead);
        }
    }
}
c# .net windows bluetooth
1个回答
0
投票

通过更新一些库和.net版本修复了它:)

© www.soinside.com 2019 - 2024. All rights reserved.