C# 读取两个唯一字符串之间的行,将它们附加到XDocument

C# 读取两个唯一字符串之间的行,将它们附加到XDocument,c#,C#,我有一个ini文件,我正在读取,我试图读取某些字符串之间的行。在本例中,我试图在节标题[SECTION1]、[SECTION2]之间获取行1=1、2=2、3=3。这两个部分之间的行数可能是可变的,因此我尝试创建一个列表,然后在仍然读取文件的情况下循环浏览。然后我需要创建这些文档并将其附加到一个XDocument中,该文档将保存在磁盘上 [SECTION1] 1=One 2=Two 3=Three [SECTION2] 4=Four 5=Five 6=Six 我现在的代码如下:

我有一个ini文件,我正在读取,我试图读取某些字符串之间的行。在本例中,我试图在节标题[SECTION1]、[SECTION2]之间获取行1=1、2=2、3=3。这两个部分之间的行数可能是可变的,因此我尝试创建一个列表,然后在仍然读取文件的情况下循环浏览。然后我需要创建这些文档并将其附加到一个XDocument中,该文档将保存在磁盘上

[SECTION1]
1=One
2=Two
3=Three

[SECTION2]
4=Four
5=Five
6=Six
我现在的代码如下:

        var lines = File.ReadAllLines(file);
        List<XElement> iniValues = null;
        string correctPath = null;
        foreach (var line in lines)
                    {
                        if (Regex.IsMatch(line, @"\[(.*?)\]"))
                        {
                            Console.WriteLine(line);
                            switch (line.Substring(1, line.IndexOf("]") - 1))
                            {
                            //Switch cases based off of the matching values

var lines=File.ReadAllLines(文件);
列表值=null;
字符串correctPath=null;
foreach(行中的var行)
{
if(Regex.IsMatch(第行@“\[(.*?\]))
{
控制台写入线(行);
开关(行子字符串(1,行索引(“]”)-1))
{
//根据匹配值的大小写切换大小写

但是我似乎无法理解如何在中间线中循环并获得线。我可以在后面分割它,但是我不能弄清楚如何在中间找到线。< /P> < P>它可以简单地通过首先找到节的索引,然后用简单的索引子项计算节长。 有了这些信息,就可以很容易地过滤出所需的行

var Lines = File.ReadAllLines(file);

// First Get the index of each section
var SectionsIndex = Lines
    .Select((l, index) => new { index, IsSection = l.StartsWith("[") }) // Instead of l.StartsWith("[") you can use any code that will match your section.
    .Where(l => l.IsSection)
    .Select(l => l.index)
    .ToList();
// => 0, 4

// Then with these indexes, calculate the index of each first content line and the length of each section
var SectionIndexAndLength = SectionsIndex
    .Zip(SectionsIndex.Append(Lines.Count).Skip(1))
    .Select(e => new {index = e.First + 1, Length = e.Second - (e.First + 1)})
    .ToList();
// => { index = 1, Length = 3} ,  { index = 5, Length = 3 }    

// Then get the corresponding lines using the above indexes and lengths.
var Result =
    SectionIndexAndLength
    .Select(e => Lines
        .Skip(e.index)
        .Take(e.Length)
        .ToList())
    .ToList();

// => "1=One", "2=Two", "3=Three" 
// => "4=Four", "5=Five", "6=Six"
然后可以使用结果轻松地构造XML。 如果需要保留节的名称,最后一个代码块可以替换为:

var Result =
    SectionIndexAndLength
    .Select(e => new {
        SectionTitle = Lines[e.index - 1],
        SectionContent = Lines
        .Skip(e.index)
        .Take(e.Length)
        .ToList()
    })
    .ToList()

// => { SectionTitle = [SECTION1], SectionContent = ("1=One", "2=Two", "3=Three") }
// => { SectionTitle = [SECTION2], SectionContent = ("4=Four", "5=Five", "6=Six") }
这对你有帮助吗?