c# - 解析配置文件C#

标签 c# parsing

我需要一些帮助来解析包含多个部分的文本文件。该文件的格式如下:

;This is a comment that should be ignored when parsing 

;Colors in 24-bit format
#define BLUE 16711680
#define RED 255

[SETTINGS]
File Name
File Description
v1.0

[SECTION]
BLUE  N033.56.09.699 W118.25.09.714

[SECTION2]
RED    N033.56.13.675 W118.24.30.908
       N033.56.13.675 W118.24.30.908
       N033.56.16.034 W118.24.07.905

基本上,我需要跳过任何评论。我还需要能够从 #define 部分提取子值。最后,我需要解析每个 header 部分下的每一行(例如 [SETTINGS][SECTION] 等)。该文件不仅限于这些 header 。

这是我现在所拥有的,但它显然不起作用。

string line;
while ((line = reader.ReadLine()) != null)
{
    string[] items = line.Split('\t');
    foreach (string item in items)
    {
        if(item.StartsWith("[SETTINGS]"))
        {

        }
        if(item.StartsWith("[SECTIOn]"))
        {

        }
    }
}

最佳答案

如果这是您想要的数据结构类型,您可以使用下面的代码......

This is what the result will pretty much look like

void Main()
{
    // Gets rid of any comments that exist in our config file
    IEnumerable<string> textLines = text.Split('\n')
                                        .Where(line => !line.StartsWith(";"));;

    // Converts our 'IEnumerable<string> textLines' back to a string without comments
    string textWithoutComments = string.Join("\n", textLines);

    // Retrieves which variables are defined
    // >> BLUE 16711680 
    // >> RED 255 
    Dictionary<string, string> definedVariables = textLines .Where(line => line.StartsWith(@"#define"))
                                                            .Select(line => Regex.Match(line, @"#define ([^ ]*) (.*)"))
                                                            .ToDictionary(match => match.Groups[1].Value, match => match.Groups[2].Value);

    // Creates a dictionary of sections that have been defined
    // >> SETTINGS      File Name
    // >>               File Description
    // >>               v1.0
    // >>
    // >> SECTION BLUE  N033.56.09.699 W118.25.09.714
    // >>
    // >> SECTION2 RED  N033.56.13.675 W118.24.30.908
    // >>               N033.56.13.675 W118.24.30.908
    // >>               N033.56.16.034 W118.24.07.905 
    Dictionary<string, string> sectionDictionary = Regex.Matches(textWithoutComments, @"\[([\w]*)\]\n([^\[^\#]*)")
                                                        .Cast<Match>()
                                                        .ToDictionary(match => match.Groups[1].Value, match => match.Groups[2].Value);


    UserConfiguration userConfig = new UserConfiguration 
    {
        Variables = definedVariables,
        Settings  = sectionDictionary["SETTINGS"],
        Sections  = sectionDictionary.Where(dictionary  => dictionary.Key != "SETTINGS")
                                    .Select(dictionary  => new {Key = dictionary.Key, Value = Regex.Match(dictionary.Value, @"(\w*) ([^\[]*)")})
                                    .ToDictionary(anon => anon.Key, anon => new Config 
                                    { 
                                        Name = anon.Value.Groups[1].Value, 
                                        Value = anon.Value.Groups[2].Value.RemoveWhiteSpace()
                                    })
    };

}
public class UserConfiguration
{
    public Dictionary<string, string> Variables { get; set; }
    public string Settings { get; set; }
    public Dictionary<string, Config> Sections { get; set; }
}

public class Config
{
    public string Name { get; set; }
    public string Value { get; set; }
}

public static class Extensions
{
    public static string RemoveWhiteSpace(this string text)
    {
        var lines = text.Split('\n');
        return string.Join("\n", lines.Select(str => str.Trim()));
    }
}

const string text = @";This is a comment that should be ignored when parsing 

;Colors in 24-bit format
#define BLUE 16711680
#define RED 255

[SETTINGS]
File Name
File Description
v1.0

[SECTION]
BLUE  N033.56.09.699 W118.25.09.714

[SECTION2]
RED    N033.56.13.675 W118.24.30.908
    N033.56.13.675 W118.24.30.908
    N033.56.16.034 W118.24.07.905";

关于c# - 解析配置文件C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26266770/

相关文章:

objective-c - Hpple 实现/无法识别的选择器

c# - 递归类的属性

c# - 将 JSON 作为 .json 文件返回

c# - 如何用C#写一个文本文件

java - Android 中将字符串解析为日期错误

parsing - 是否可以将这个文法转化为LR(1)文法?

forms - 高效的算法/方法来解析(没有任何框架)多部分/表单数据请求而不将所有内容读取到内存中?

c# - 使用 async/await 时防止 winforms UI 阻塞

c# - 在没有网络连接的情况下发送数据包(无线适配器)

vb.net - 日期格式问题