Parsing multiple sections of a C # text file

First, let me start by thanking you for participating in this site, I have already received so much useful information from it. including some basic analysis of text files in arrays, but now I want to take another step.

I have a text file that looks something like this:

Start Section 1 - foods

apple  
bannana  
pear   
pineapple  
orange  

end section 1

Start section 2 - animals

dog  
cat  
horse  
cow  

end section 2 

what I want to do is use one file read by copying the data from section 1 to an array called "products" and section 2 to and an array called "animals"

now I can get it to work, using a new loop for each section, closing and reopening the file each time, looping until I find the section I want and creating an array.

, .

List<string> typel = new List<string>();  

using (StreamReader reader = new StreamReader("types.txt")) // opens file using streamreader
        {

            string line; // reads line by line in to varible "line"
            while ((line = reader.ReadLine()) != null) // loops untill it reaches an empty line
            {
                typel.Add(line); // adds the line to the list varible "typel"
                               }

        }

        Console.WriteLine(typel[1]);  // test to see if list is beeing incremented
        string[] type = typel.ToArray(); //converts the list to a true array 
        Console.WriteLine(type.Length); // returns the number of elements of the array created. 

- , , .

, .

,

while ((line = reader.ReadLine()) != Start Section 1 - foods)  
{  
}  
while ((line = reader.ReadLine()) != end Section 1)   
{  
foods.Add(line);  
}  
...  
....

" 1 - " . , , ?

. .

+5
4

. , ..

, :

class Program
{
    private static Dictionary<string, List<string>> _arrayLists = new Dictionary<string, List<string>>();

    static void Main(string[] args)
    {
        string filePath = "c:\\logs\\arrays.txt";
        StreamReader reader = new StreamReader(filePath);
        string line;
        string category = "";

        while (null != (line = reader.ReadLine()))
        {
            if (line.ToLower().Contains("start"))
            {
                string[] splitHeader = line.Split("-".ToCharArray());
                category = splitHeader[1].Trim();
            }
            else
            {
                if (!_arrayLists.ContainsKey(category))
                {
                    List<string> stringList = new List<string>();
                    _arrayLists.Add(category, stringList);
                }

                if((!line.ToLower().Contains("end")&&(line.Trim().Length > 0)))
                {
                    _arrayLists[category].Add(line.Trim());
                }
            }
        }

        //testing
        foreach(var keyValue in _arrayLists)
        {
            Console.WriteLine("Category: {0}",keyValue.Key);
            foreach(var value in keyValue.Value)
            {
                Console.WriteLine("{0}".PadLeft(5, ' '), value);
            }
        }


        Console.Read();
    }
}
+3

, . System.IO.ReadAllLines(fileName) .

( ) :

// totally untested
Dictionary<string, List<string>> sections = new Dictionary<string, List<string>>();
List<string> section = null;

foreach(string line in GetLines())
{
   if (IsSectionStart(line))
   {
      string name = GetSectionName(line);
      section = new List<string>();
      sections.Add(name, section);
   }
   else if (IsSectionEnd(line))
   {          
      section = null;  // invite exception when we're lost
   }
   else
   {
      section.Add(line);
   }
}


...
List<string> foods = sections ["foods"];
+4

, , , :

var regex = new Regex(@"Start Section \d+ - (?<section>\w+)\r\n(?<list>[\w\s]+)End Section", RegexOptions.IgnoreCase);

var data = new Dictionary<string, List<string>>();

foreach (Match match in regex.Matches(File.ReadAllText("types.txt")))
{
    string section = match.Groups["section"].Value;
    string[] items = match.Groups["list"].Value.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

    data.Add(section, new List<string>(items));
}

// data["animals"] now contains a list of "dog", "cat", "horse", and "cow"

:

"" (, ), ;) , , , ?

, "" " ", . - , . , , , "", , , , ? , , ... , .

+2

, ?

//converting it to array called allLines, elements/index per line
string[] allLines = File.ReadAllLines("types.txt").ToArray();

//getting the index of allLines that contains "Start Section 1" and "end section 1" 
int[] getIndexes = new int[] { Array.FindIndex(allLines, start => start.Contains("Start Section 1")), Array.FindIndex(allLines, start => start.Contains("end section 1")) };

//create list to get indexes of the list(apple,banana, pear, etc...)
List<int> indexOfList = new List<int>();

//get index of the list(apple,banana, pear,etc...)
for (int i = getIndexes[0]; i < getIndexes[1]; i++)
{
    indexOfList.Add(i);
}

//remove the index of the element or line "Start Section 1"
indexOfList.RemoveAt(0);
//final list
string[] foodList = new string[]{ allLines[indexOfList[0]], allLines[indexOfList[1]], and so on...};

Then you can call them or change, and then save.

//call them
Console.Writeline(foodList[0] + "\n" + foodList[1] + ...)

//edit the list
allLines[indexOfList[0]] = "chicken"; //from apple to chicken
allLines[indexOfList[1]] = "egg"; //from banana to egg
//save lines
File.WriteAllLines("types.txt", allLines);
0
source

All Articles