首页 > 解决方案 > 如何解析文本文件c#并获得正确的结果数据

问题描述

我正在解析一个文本文件以获取蓝牙的设置数据:

该值可以被禁用或启用并用 * 标记。

我遇到的问题是它总是返回状态为“启用”,不管它是否被禁用。

这可能是因为它读取的文本在缩进的行前面有一个制表符。我怎样才能纠正这个工作?

  private String GetBluetoothStatus(String FilePath)
{
    String[] lines = File.ReadAllLines(FilePath);
    int index = 0;
    string status = "";
    foreach (String s in lines)
    {
        if (s == "Bluetooth")
        {
            if (lines[index + 1].StartsWith("*"))
                status = "Disabled";
            else
                status = "Enabled";
            return status;
        }
        index += 1;
    }
    return status;
}

文本文件如下:

BIOSConfig 1.0
;
;     Originally created by BIOS Configuration Utility
;     Version: 4.0.25.1
;     Date="2018/08/06" Time="15:42:35" UTC="-5"
;
;     Found 182 settings
;
Power On When AC Detected
    *Disabled
    Enabled
Power On When Lid is Opened
    *Disabled
    Enabled
Fast Boot
    *Disable
    Enable
Bluetooth
    Disabled
    *Enabled
Wireless Network Device (WLAN)
    Disabled
    *Enabled
LAN / WLAN Auto Switching
    Disabled
    *Enabled

标签: c#parsing

解决方案


更改以下行

if (lines[index + 1].StartsWith("*"))

  if (lines[index + 1].Trim().StartsWith("*Disabled"))

Contains像你提到的那样更好地使用也Enable Disable可以出现在同一行中。

if (lines[index + 1].Contains("*Disabled"))

推荐阅读