如何使用相同的关键字逐行索引多个文本?

时间:2019-06-02 09:47:01

标签: c#

我在阅读文本文件时遇到问题。问题是我无法为某些相同的文本编制索引。

这是我要索引的文本的示例

add_ace resource.essentialmode command.sets allow
add_ace resource.essentialmode command.add_principal allow
add_ace resource.essentialmode command.add_ace allow

# These resources will start by default.
start mapmanager
start chat
start spawnmanager
start sessionmanager
start fivem
start hardcap
start rconlog
#start scoreboard
#start playernames
start bob74_ipl

我尝试使用File.ReadAllLines()方法。但是我只能读取所有行或特定行。 这里的代码

string[] readText = File.ReadAllLines("indextext.txt");
    foreach (string s in readText)
    {  //Read All line
        Console.WriteLine(s);
    }
    //Read Spesific line
    Console.writeline(readText[1]);

我想要的是读取以“ start”开头的文本行。因此结果保存到字符串数组中

//first index
start mapmanager

//second index
start chat

etc.

但我不知道执行此操作的代码或功能。帮帮我

3 个答案:

答案 0 :(得分:0)

如果我对您的理解正确,那么您想读取一个文件并提取所有以关键字“ start”开头的行并将它们存储在集合中。如果是这样的话:

var commands = new List<string>();

using (var sr = new StreamReader("PATH TO FILE"))
{
    var line = sr.ReadLine();

    while (line != null)
    {
        if (line.ToLower().StartsWith("start "))
        {
            commands.Add(line);
        }

        line = sr.ReadLine();
    }
}

答案 1 :(得分:0)

尝试以下操作:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.txt";
        static void Main(string[] args)
        {
            StreamReader reader = new StreamReader(FILENAME);
            string line = "";
            while((line = reader.ReadLine()) != null)
            {
                if(line.StartsWith("start"))
                {
                    string[] splitArray = line.Split(new char[] { ' ' }).ToArray();
                    Console.WriteLine(splitArray[1]);
                }
            }
            Console.ReadLine();
        }
    }
}

答案 2 :(得分:0)

基本上,您无法有条件地从不知道的内容中读取内容,因此您至少需要读取一行,然后将该条件应用于已读取的行中。

我建议以有助于分离关注点的方式实施此操作,从而为您提供更大的灵活性。

// Flexible strategy you can tinker with and change without affecting the main program.
public class LineSelectionStrategy
{
    public bool LineMeetsCondition(string line)
    {
        if (string.IsNullOrEmpty(line))
            return false;
        return line.StartsWith("start"); // Add your condition here
    }
}

// Represents a command in a text file comprised of an execution function
// and a command / app / action to run with that function.
public class TextCommand
{
    public string Function { get; }
    public string Action { get; }

    private readonly char[] _commandSeparators = { ' '};

    public TextCommand(string textLine)
    {
        var elements = textLine.Split(_commandSeparators, StringSplitOptions.RemoveEmptyEntries);
        Function = elements.FirstOrDefault();
        Action = elements.LastOrDefault();
    }
}

模型和策略类...

{{1}}