How to read a part of a text file and put them in an array in c#
0 #1 1 Day Ago
I have a text file including several strings and doubles. I want to find a specific string in the text and read all double numbers after it which are located between two slashes"/". The number of double data could be unknown-but we just know they are bounded with two slashes- the file is two big and including several strings for example my data file is like this and I want to put all Double numbers,bounded between slashes and after "POROSITY" into an array with name "POROSITY".
*****************************************************
Permeability
/
1 2 3 4
5 6 7 8
9 10
11 12 13 14
15 15 17 18
19 20
21 22 23 24
25 26 27 28
29 30
.
.
.
/
POROSITY
/
1 2 3 4
5 6 7 8
9 10
11 12 13 14
15 15 17 18
19 20
21 22 23 24
25 26 27 28
29 30
.
.
.
/

Dani AI

Generated

Brief summary and a robust alternative approach.

As recommended, treat the slash (/) lines as table delimiters and locate the header (POROSITY) first. 's working example shows a full implementation that builds a dictionary of named blocks. The following notes and sample show a streaming, regex-based alternative that avoids loading the entire file, tolerates stray whitespace (for example the sample has "/ "), and parses floating-point values reliably.

The approach

  • Stream the file line by line to keep memory usage low.
  • Find the header line (case-insensitive), skip to the next slash, then collect lines until the next slash is reached.
  • Use a regex to extract numeric tokens (handles integers, decimals and scientific notation).
  • Parse with CultureInfo.InvariantCulture and optionally fall back to the current culture if comma decimals are expected.
  • Stop after the first matching block or continue collecting if multiple blocks with the same name are required.

Example (streaming + regex, C#):

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

public static double[] ReadSectionNumbers(string path, string sectionName)
{
    using (var sr = new StreamReader(path))
    {
        string line;
        bool foundHeader = false, inBlock = false;
        var sb = new StringBuilder();
        while ((line = sr.ReadLine()) != null)
        {
            string t = line.Trim();
            if (!foundHeader)
            {
                if (string.Equals(t, sectionName, StringComparison.OrdinalIgnoreCase))
                    foundHeader = true;
            }
            else if (!inBlock)
            {
                if (t.StartsWith("/")) inBlock = true;
            }
            else
            {
                if (t.StartsWith("/")) break;
                sb.AppendLine(t);
            }
        }

        var matches = Regex.Matches(sb.ToString(), @"-?\d+(\.\d+)?([eE][+-]?\d+)?");
        var list = new List<double>(matches.Count);
        foreach (Match m in matches)
            if (double.TryParse(m.Value, NumberStyles.Float, CultureInfo.InvariantCulture, out double v) ||
                double.TryParse(m.Value, NumberStyles.Float, CultureInfo.CurrentCulture, out v))
                list.Add(v);
        return list.ToArray();
    }
}

Troubleshooting tips

  • Watch for trailing spaces on slash lines; use Trim or StartsWith("/") as above.
  • If the file is truly enormous and only one section is needed, the streaming version exits early and is efficient.
  • If numeric formatting includes commas as decimal separators, parse with the appropriate CultureInfo.
  • For malformed lines, log or skip tokens rather than throwing exceptions.

Recommended Answers

All 2 Replies

Read file, when you read POROSITY read "/"
Then read all following chars until "/" into a string array.
Don't know with what chars your doubles are separated, but if you know, use the string.Split method to separate all doubles in an array.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace daniweb
{
  public partial class frmDoubleRead : Form
  {
    public frmDoubleRead()
    {
      InitializeComponent();
    }

    private static string[] GetTestData()
    {
      List<string> result = new List<string>();
      result.Add("Permeability");
      result.Add("/");
      result.Add("1 2 3 4");
      result.Add("5 6 7 8");
      result.Add("9 10");
      result.Add("11 12 13 14");
      result.Add("15 15 17 18");
      result.Add("19 20");
      result.Add("21 22 23 24");
      result.Add("25 26 27 28");
      result.Add("29 30");
      result.Add(".");
      result.Add(".");
      result.Add(".");
      result.Add("/");
      result.Add("POROSITY");
      result.Add("/");
      result.Add("1 2 3 4");
      result.Add("5 6 7 8");
      result.Add("9 10");
      result.Add("11 12 13 14");
      result.Add("15 15 17 18");
      result.Add("19 20");
      result.Add("21 22 23 24");
      result.Add("25 26 27 28");
      result.Add("29 30");
      result.Add(".");
      result.Add(".");
      result.Add(".");
      result.Add("/ ");
      return result.ToArray();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      Dictionary<string, List<int>> dict = new Dictionary<string, List<int>>(StringComparer.CurrentCultureIgnoreCase);

      const string TABLE_BEGIN = @"/";
      //string[] lines = System.IO.File.ReadAllLines(@"C:\data.txt");
      string[] lines = GetTestData();

      string curTable = string.Empty;
      List<int> curWorkingSet = null;

      for (int i1 = 0; i1 < lines.Length; i1++)
      {
        string trimmedLine = (string.IsNullOrEmpty(lines[i1]) ? string.Empty : lines[i1].Trim());
        if (trimmedLine.Equals(TABLE_BEGIN))
        {
          if (string.IsNullOrEmpty(curTable))
          {
            curTable = lines[i1 - 1];
            if (!dict.TryGetValue(curTable, out curWorkingSet))
            {
              curWorkingSet = new List<int>();
              dict.Add(curTable, curWorkingSet);
            }
          }
          else
            curTable = string.Empty;
        }
        string[] lineFields = trimmedLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        foreach (string s in lineFields)
        {
          int i;
          if (int.TryParse(s, out i))
            curWorkingSet.Add(i);
        }
      }

      foreach (KeyValuePair<string, List<int>> kvp in dict)
      {
        string key = kvp.Key;
        int[] iValues = kvp.Value.ToArray();
        string[] sValues = Array.ConvertAll<int, string>(iValues, Convert.ToString);
        Console.WriteLine("{0}: {1}",
          key,
          string.Join(", ", sValues));
      }
    }

  }
}

Results in:

Permeability: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 15, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30
POROSITY: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 15, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30
commented: i would give my left nut to have your code library! :p +1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.