C# Считать вывод консоли снизу вверх до пустой строки - PullRequest
0 голосов
/ 29 апреля 2020

Я создаю C# консольное приложение для чтения имен устройств из serialPort. Мне удалось распечатать все подключенные имена устройств на консоли. Вывод консоли выглядит следующим образом:

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);

1 Ответ

2 голосов
/ 29 апреля 2020

Когда вы читаете из последовательного порта, вы можете сохранить его в строковой переменной.

Затем обработать строковую переменную, разделив ее на массив на основе разрывов строки.

Итерировать по элементы массива и берут только те, которые начинаются с числа, разделенного точкой полного пробела.

Те строки, которые вы хотите, сохраните в Словаре, используя индекс, предоставленный методом ReadExisting(), в качестве индекса словаря. Это необходимо для того, чтобы назначить идентификатор устройству, чтобы при выборе пользователем идентификатора пользователя можно было выполнить обратный поиск по его идентификатору.

Затем l oop Словарь для отображения устройств на консоль.

Сохранение идентификатора, выбранного пользователем, и обратный поиск устройства по идентификатору с использованием словаря.

Я предполагаю, что у вас есть средства для доступа к списку устройств в списке Enumerable.

    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];
    }
...