如何从多个文件中提取文本

时间:2018-02-08 02:04:13

标签: c#

我需要从文件中提取特定序列的200个文件,并将结果写入新的csv文件中。我只是在学习C#,但在过去有很多其他语言的经验。我已经尝试查找所有单独的步骤,以及我不明白的正则表达,但我不知道如何将它们拼接在一起。 示例文本:

  

- > SAT1_988_Connection_Verify

     
    

EA0683010A01030F15A40202004E2000

         

E0068300

         

E40683010278053A

  
     

>

     

(S45,10:38:35 AM)

算法步骤

 1) I need to point the program at a directory with the files.
 2) I need the program to search through each file in the directory.
 3) I need to find the lines that starts with "E40", of which there could be multiple or none.  Additionally, this line varies in length.
 4) I need to grab that line, as well as the two before it, which are highlighted in the nested block quote above.
 5) There is always a blank line after the target line.
 6)I need to write those three lines separated by commas in a text document.

到目前为止我的代码:

using System;
using System.Collections.Generic;
using System.IO;

namespace ConsoleApplication2
{
class Program
{
    static void Main()
    {
        string path = @"C:\ETT\Test.txt";
        string[] readText = File.ReadAllLines(path);
        foreach (string s in readText)
        {

        }
    }
  public static string getBetween(string[] strSource, string strKey)
    {
        int Start, End;
      if (strSource.Contains(strKey))
      {
          Start = Array.IndexOf(strSource, strKey) -2;
          End = Array.IndexOf(strSource, strKey) + 1;
          return strSource.Substring(Start, End - Start);
      }
      else
      {
          return "";
      }
    }
}
}

1 个答案:

答案 0 :(得分:0)

有很多方法可以做到这一点。然而,只是为了帮助您(并且因为您为第一篇文章添加了相对详细的信息量,您需要查找以下主题

Directory.EnumerateFiles Method

  

返回与搜索匹配的可枚举文件名集合   指定路径中的模式。

File.ReadAllLines Method

  

打开文本文件,将文件的所有行读入字符串数组,   然后关闭文件。

Enumerable.Where<TSource> Method (IEnumerable, Func)

  

根据谓词过滤一系列值。

String.StartsWith Method

  

确定此字符串实例的开头是否与a匹配   指定的字符串。

https://joshclose.github.io/CsvHelper/

  

用于读取和写入CSV文件的库。非常快速,灵活,   而且易于使用。支持读写自定义类对象。   CSV助手实现RFC 4180.默认情况下,它非常保守   它的写作,但在阅读中非常自由。有一大套   可以用来改变读写方式的配置   行为,使您能够读/写非标准文件。

唯一棘手的部分是在

之前获得3行

List<T>.IndexOf Method (T)

  

搜索指定的对象并返回从零开始的索引   整个List中的第一次出现。

从该索引中,您可以使用List[Index-1] List[Index-2]获取前面的行

祝你好运。

相关问题