Skip to main content
 首页 » 编程设计

c#之将文本文件解析为字典

2024年02月20日12mayingbao

我有一个包含数百个配置值的文本文件。配置数据的一般格式是“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 

请您参考如下方法:

这是一个不错的小脑袋。我认为这段代码可能能够为您指明正确的方向。请记住,这会填充 Dictionary<string, string> ,因此没有将值转换为整数等。另外,请原谅困惑(以及糟糕的命名约定)。这是根据我的思路快速撰写的文章。

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