用新行解析字符串并获取值

时间:2019-11-22 19:30:16

标签: asp.net-core-3.0

我有一个文件需要读取,该文件包含键和值,该文件只是普通的旧.txt文件,“键”和“值”之间的空格数量可能有所不同,并且所需的键可以以任何顺序,我将进行以下单元测试:

    [Fact]
    public void ReadStatus_Should_GetStatus()
    {
        //Arrange
        var content =
        @"$filename  @FFBASE\\image\00001154.TIF" + Environment.NewLine +
        @"$cover     @FFBASE\\copia.gct" + Environment.NewLine +
        @"$header    'Please deliver to @ROUTETO'" + Environment.NewLine +
        @"$sender    'Dorothy'" + Environment.NewLine +
        @"$receiver  'Ann Other'" + Environment.NewLine +
        @"$status1   2" + Environment.NewLine +
        @"$status2   0" + Environment.NewLine +
        @"$send_time 17:00:00" + Environment.NewLine +
        @"$phone     3105553218" + Environment.NewLine;


        var target = CreateTarget();

        // Act
        var status = target.ReadStatus(content);

        //Assert
        Assert.Equal(Status.AStatus, status);
    }

还有ReadStatus方法(我尝试了但不起作用:

public Status ReadStatus(string content)
{
    Dictionary<string, string> dictionary = new Dictionary<string, string>();

    dictionary = dictionary.ToDictionary(
        k => k.Key,
        v => v.Value.Replace(Environment.NewLine, v.Value.ToString()));

    string statusOne = dictionary["status1"].ToString();
    string statusTwo = dictionary["status2"].ToString();

    return Status.AStatus;
}

这个想法是要获得status1status2的值,它们的值可以是任意值,并且空格的数量可以是任意的。

编辑: 好吧,我的方法演变成这样:         公共状态ReadStatus(字符串内容)         {             IList contentList = content.Split(Environment.NewLine);

        string statusOne = contentList
            .Where(s => s.StartsWith("$fax_status1"))
            .FirstOrDefault();

        string statusTwo = contentList
            .Where(s => s.StartsWith("$fax_status2"))
            .FirstOrDefault();

        return Status.AStatus;
    }

现在的想法是获取正确的元素,例如,我现在有"status1 2""status2 0"。也许是通过消除键并保留空白空间来实现的?

0 个答案:

没有答案