How to get specific text from a txt file in C#?

Asked

Viewed 66 times

0

I’m a layman, still taking the first steps in programming and C# and I’m having trouble solving a problem.

I would like to search a specific information in a txt file with the following lines:

Nodal force point

15  25  30

20  35  13

25  85  25


Nodal Moment point

23  58  6

6   4   5   

3   2   1

Nodal displacements point

25  1   5

2   5   4

6   4   5

Well, I need to identify the "Nodal Moment point" and store the second row value (In that case, the 4).

Note: It will not necessarily be 4, since they are randomly generated values. Ah, the file will always follow this pattern (Each title will have 3 rows of data, it will always have a blank row and the columns are separated by 2 spaces)

I am using the following code to locate the part of the file that contains the "Nodal Moment point":

var valor = File.ReadAllLines("NomeDoArquivo.txt")
                .Where(l=>l.StartsWith("Nodal Moment"))

However, I don’t know how to find the second value of the second line and store in the variable.

I thank you in advance for your help.

  • 1

    There is no way to help you without knowing more details about the file format. Will each title have 3 lines of data? After the title will always have a blank line (in the last title has 2)? Columns will always be separated by 2 spaces?

  • You’re right. Each title will have 3 rows of data, it will always have a blank row and the columns are separated by 2 spaces. Always following this pattern.

  • I will correct the posting. Thank you for the comment!

2 answers

0

class Program
{
    static void Main(string[] args)
    {
        string arquivo = @"C:\temp\teste.txt";

        if(File.Exists(arquivo))
        {
                try
                {
                    string[] listTxt = File.ReadAllLines(arquivo);
                    var strList = listTxt[13];
                    var values = strList.Split("  ");
                    var result = values[1];
                }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        Console.ReadKey();
    }
}
  • Thank you very much for the answer, it will help a lot!

0


The algorithm is simple:

  • File.ReadAllLines("file.txt"): Read the text file.
  • SkipWhile(l => l != "Nodal Moment point"): Discard all lines until you find the string "Nodal Moment point".
  • Except(new string[]{""}): Remove all empty lines.
  • Skip(1): Discard the line containing the string "Nodal Moment point".
  • TakeWhile(l => Char.IsNumber(l[0])): Pick up the lines while the first character is numeric and discard all lines including and after finding the first line whose first character is not numeric.
  • Select((l,_) => l.Split(" ", StringSplitOptions.RemoveEmptyEntries)): For the remaining lines to explode them into spaces in string arrays discarding empty strings.
  • ToArray(): Join the result in a row-by-column array.

Remembering that arrays in C# begin at index 0.
So if you want the third element of the first line data[0][2].

using System;
using System.IO;
using System.Linq;

class MainClass {
  public static void Main (string[] args) {
    var data = File.ReadAllLines("file.txt")       
       .SkipWhile(l => l != "Nodal Moment point")
       .Except(new string[]{""})
       .Skip(1)
       .TakeWhile(l => Char.IsNumber(l[0]))
       .Select((l,_) => l.Split(" ", StringSplitOptions.RemoveEmptyEntries))
       .ToArray();
    Console.WriteLine(data[1][1]);    //4
  }
}

Test the example on Repl.it

Visualization of what each function does:

  • File.ReadAllLines("file.txt")
Nodal force point

15  25  30

20  35  13

25  85  25


Nodal Moment point

23  58  6

6   4   5   

3   2   1

Nodal displacements point

25  1   5

2   5   4

6   4   5
  • SkipWhile(l => l != "Nodal Moment point")
Nodal Moment point

23  58  6

6   4   5   

3   2   1

Nodal displacements point

25  1   5

2   5   4

6   4   5
  • Except(new string[]{""})
Nodal Moment point
23  58  6
6   4   5
3   2   1
Nodal displacements point
25  1   5
2   5   4
6   4   5
  • Skip(1)
23  58  6
6   4   5
3   2   1
Nodal displacements point
25  1   5
2   5   4
6   4   5
  • TakeWhile(l => Char.IsNumber(l[0]))
23  58  6
6   4   5
3   2   1
  • Select((l,_) => l.Split(" ", StringSplitOptions.RemoveEmptyEntries))
Array<String>["23","58","6"]
Array<String>["6","4","5"]
Array<String>["3","2","1"]
  • ToArray();
data = [["23","58","6"], ["6","4","5"], ["3","2","1"]]

References:

  • 1

    Fantastic explanation. I really appreciate your help. I’ll take the test and come back for feedback. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.