【问题标题】:C# Read console output from bottom to top, until empty lineC#从下到上读取控制台输出,直到空行
【发布时间】:2020-04-29 08:56:57
【问题描述】:

我正在构建 C# 控制台应用程序以从 serialPort 读取设备名称。我设法将所有连接的 deviceNames 打印到控制台。控制台输出如下所示:

Scanning...
---------------------------------
Connected devices:

1. DeviceName1
2. DeviceName2
3. DeviceName3

现在,如何从下到上读取输出,直到第一个空行?而不是让Console.ReadLine() 让用户可以通过在 deviceName 前面输入数字来选择设备。

这是我正在使用的代码:

var serialPort = new System.IO.Ports.SerialPort()
// Read the data that's in the serial buffer.
var deviceName = serialPort.ReadExisting();

// Write to debug output.
Console.WriteLine($"\n---------------------------------");
Console.WriteLine($"\nConnected devices:\n");
Console.WriteLine(deviceName);

string input;
do
{
    // Here I need posibility for user
    // to type number infront deviceName

} while (deviceName.ToUpper() != null);

【问题讨论】:

  • 你确定需要解析控制台输出来获取想要的数据吗?从串口读取并打印到控制台的当前代码是什么样的?听起来你的事情过于复杂了。
  • 我已将蓝牙加密狗连接到 SerialPort。我发出命令dongle list-device。比我得到有问题的输出。现在我需要向选定的设备发送消息。
  • 我用从 SerialPort 读取和打印到控制台的代码更新了问题。

标签: c# .net console console-application


【解决方案1】:

当你从串口读取时,你可以将它存储在一个字符串变量中。

然后处理字符串变量,根据换行符将其拆分为数组。

遍历数组项,只取那些以数字开头并用句号分隔的项。

将您想要的那些行存储到 Dictionary 中,使用ReadExisting() 方法提供的索引作为您的 Dictionary 索引。 这是为了允许您为设备分配一个 ID,以便当用户选择 ID 时,您可以通过其 ID 反向查找设备。

然后,循环字典以将设备显示到控制台。

捕获用户选择的 ID,然后使用 Dictionary 按 ID 反向查找设备。

我假设您有办法访问可枚举列表中的设备列表。

    public static void Main(string[] args)
    {
        // Can't simulate the output. So, I assume there is an output from ReadExisting(), and I capture the output to a string variable.
        // var serialPort =  new System.IO.Ports.SerialPort();
        // var outputReadExisting = serialPort.ReadExisting();
        var outputReadExisting = @"Scanning...
-------------------------------- -
Connected devices:

1.DeviceName1
2.DeviceName2
3.DeviceName3";

        var deviceDict = LoadDevicesToDictionary(outputReadExisting);
        DisplayDevices(deviceDict);
        var selectedDevice = PromptUserToSelectDevice(deviceDict);

    }

    private static Dictionary<int, string> LoadDevicesToDictionary(string output)
    {
        var outputLines = output.Split(new[] { Environment.NewLine, "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);

        var deviceDict = new Dictionary<int, string>();
        foreach (var line in outputLines)
        {
            // Skip line if null/whitespace or if it does not contains "." (the index)
            if (string.IsNullOrWhiteSpace(line) || !line.Contains("."))
            {
                continue;
            }

            var splitLine = line.Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries);
            // Skip line if after splitting by number and first part is not an integer (not device index)
            if (splitLine.Length < 2 || !int.TryParse(splitLine[0], out var deviceIndex))
            {
                continue;
            }

            // Add device index as dictionary index, then take remainder string minus the device index and the "."
            deviceDict.Add(deviceIndex, line.Substring(deviceIndex.ToString().Length + 1));
        }
        return deviceDict;
    }

    private static void DisplayDevices(Dictionary<int, string> deviceDict)
    {
        foreach (var device in deviceDict)
        {
            Console.WriteLine($"{device.Key}. {device.Value}");
        }
    }

    private static string PromptUserToSelectDevice(Dictionary<int, string> deviceDict)
    {
        Console.WriteLine("Please select your device (ID): ");
        var selectedId = Console.ReadLine();
        if (!int.TryParse(selectedId, out var idVal)
            || !deviceDict.ContainsKey(idVal))
        {
            Console.WriteLine("Invalid input. Please input device ID listed above.");
            return PromptUserToSelectDevice(deviceDict);
        }

        return deviceDict[idVal];
    }

【讨论】:

  • 这是从控制台输出中获取设备后选择设备的好方法。但是我仍然有如何提取设备名称的问题,就像我在问题中所说的那样。
  • @AppleFan 你能和我分享一下,你如何获得serialPort对象?如,您正在使用哪个库来执行dongle list-device 命令?
  • 我更新了问题。我正在使用 System.IO.Ports。那不是问题...问题是如何从控制台获取输出并创建字典。如果我可以从最后一行、控制台输出到第一个空行获取字符串,那么我可以解析字符串并制作字典。
  • @AppleFan 我尝试在我的机器上使用ReadExisting(),但我无法生成输出。所以我模拟了数据,但它应该是一样的。我已经更新了我的代码。您检查它是否满足您的需求。如果它解决了您的问题,请将其标记为答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-12
  • 2018-08-14
  • 1970-01-01
  • 1970-01-01
  • 2019-12-24
  • 2023-03-21
相关资源
最近更新 更多