如何在c#中从行号()读取到行开头

本文关键字:读取 开头 | 更新日期: 2023-09-27 18:12:12

假设我有一个这样的文本文件

<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>-开头的行之前的文本文件

我使用string[] lines = System.IO.File.ReadAllLines(Filepath);来生成数组中的每一行问题是我只想要数组中第一部分的数字,以便稍后将它们分开到另外3个数组(hPa, m, C)。

如何在c#中从行号()读取到行开头

这是一个可能的解决方案。这可能比它应该更复杂,但这应该给你一个可能的机制来进一步完善你的数据的想法。

        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
        }

你是这个意思吗?

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.