如何读取从行号()到行开头用C#

时间:2013-05-06 08:45:29

标签: c# arrays readline

假设我有这样的文本文件

<pre>----------------

    hPa     m      C 
---------------------
 1004.0     28   13.6
 1000.0     62   16.2
  998.0     79   17.2
  992.0    131   18.0
<pre>----------------
Sometext here

 1000.0     10   10.6
 1000.0     10   11.2
  900.0     10   12.2
  900.0    100   13.0
<aaa>----------------

如何在C#中创建数据,从第5行(1004.0)读取文本文件到以字符串<pre>-开头的行

我使用了字符串[] lines = System.IO.File.ReadAllLines(Filepath); 在数组中创建每一行 问题是我只需要数组中第一部分的数字,以便稍后将它们分成另外3个数组(hPa,m,C)。

2 个答案:

答案 0 :(得分:0)

你是说这个吗?

System.IO.StreamReader file = new System.IO.StreamReader(FILE_PATH);

int skipLines = 5;
for (int i = 0; i < skipLines; i++)
{
    file.ReadLine();
}

// Do what you want here.

答案 1 :(得分:0)

这是一个可能的解决方案。它可能比应该更复杂,但这应该让您了解可能的机制,以进一步优化您的数据。

        string[] lines = System.IO.File.ReadAllLines("test.txt");
        List<double> results = new List<double>();
        foreach (var line in lines.Skip(4))
        {
            if (line.StartsWith("<pre>"))
                break;
            Regex numberReg = new Regex(@"\d+(\.\d){0,1}");  //will find any number ending in ".X" - it's primitive, and won't work for something like 0.01, but no such data showed up in your example
            var result = numberReg.Matches(line).Cast<Match>().FirstOrDefault();  //use only the first number from each line. You could use Cast<Match>().Skip(1).FirstOrDefault to get the second, and so on...
            if (result != null)
                results.Add(Convert.ToDouble(result.Value, System.Globalization.CultureInfo.InvariantCulture));  //Note the use of InvariantCulture, otherwise you may need to worry about , or . in your numbers
        }