将文本文件解析为字典

1 c# parsing text dictionary file

我有一个包含数百个配置值的文本文件.配置数据的一般格式是"Label:Value".使用C#.net,我想阅读这些配置,并在代码的其他部分使用值.我的第一个想法是,我会使用字符串搜索来查找标签,然后解析标签后面的值并将它们添加到字典中,但考虑到我必须搜索的标签/值的数量,这似乎相当繁琐.我有兴趣听听有关可能的架构来执行此任务的一些想法.我已经包含了一小部分示例文本文件,其中包含一些标签和值(如下所示).几个注意事项:值并不总是数字(如AUX序列号中所示); 不管出于什么原因 文本文件使用空格(\ s)而不是制表符(\ t)格式化.提前感谢您花时间考虑这个问题.

示范文本:

 AUX Serial Number:  445P000023       AUX Hardware Rev:           1

 Barometric Pressure Slope:     -1.452153E-02
 Barometric Pressure Intercept: 9.524336E+02
Run Code Online (Sandbox Code Playgroud)

Ich*_*lay 5

这是一个不错的小脑痒.我认为这段代码可能会指出你正确的方向.请记住,这填补了a Dictionary<string, string>,因此没有将值转换为int或类似内容.另外,请原谅一塌糊涂(以及糟糕的命名惯例).根据我的思路,这是一个快速的写作.

Dictionary<string, string> allTheThings = new Dictionary<string, string>();

public void ReadIt()
{
    // Open the file into a streamreader
    using (System.IO.StreamReader sr = new System.IO.StreamReader("text_path_here.txt"))
    {
        while (!sr.EndOfStream) // Keep reading until we get to the end
        {
            string splitMe = sr.ReadLine();
            string[] bananaSplits = splitMe.Split(new char[] { ':' }); //Split at the colons

            if (bananaSplits.Length < 2) // If we get less than 2 results, discard them
                continue; 
            else if (bananaSplits.Length == 2) // Easy part. If there are 2 results, add them to the dictionary
                allTheThings.Add(bananaSplits[0].Trim(), bananaSplits[1].Trim());
            else if (bananaSplits.Length > 2)
                SplitItGood(splitMe, allTheThings); // Hard part. If there are more than 2 results, use the method below.
        }
    }
}

public void SplitItGood(string stringInput, Dictionary<string, string> dictInput)
{
    StringBuilder sb = new StringBuilder();
    List<string> fish = new List<string>(); // This list will hold the keys and values as we find them
    bool hasFirstValue = false;

    foreach (char c in stringInput) // Iterate through each character in the input
    {
        if (c != ':') // Keep building the string until we reach a colon
            sb.Append(c);
        else if (c == ':' && !hasFirstValue)
        {
            fish.Add(sb.ToString().Trim());
            sb.Clear();
            hasFirstValue = true;
        }
        else if (c == ':' && hasFirstValue)
        {

            // Below, the StringBuilder currently has something like this:
            // "    235235         Some Text Here"
            // We trim the leading whitespace, then split at the first sign of a double space
            string[] bananaSplit = sb.ToString()
                                     .Trim()
                                     .Split(new string[] { "  " },
                                            StringSplitOptions.RemoveEmptyEntries);

            // Add both results to the list
            fish.Add(bananaSplit[0].Trim());
            fish.Add(bananaSplit[1].Trim());
            sb.Clear();
        }                    
    }

    fish.Add(sb.ToString().Trim()); // Add the last result to the list

    for (int i = 0; i < fish.Count; i += 2)
    {
        // This for loop assumes that the amount of keys and values added together
        // is an even number. If it comes out odd, then one of the lines on the input
        // text file wasn't parsed correctly or wasn't generated correctly.
        dictInput.Add(fish[i], fish[i + 1]); 
    }
}
Run Code Online (Sandbox Code Playgroud)