如何从文本文件中检索数据

时间:2017-11-05 11:41:52

标签: c#

我在所有已确认的交易的文本文件中逐行附加数据。我想添加搜索功能,用户输入他们的电子邮件地址,并且必须显示与该电子邮件相关的所有相关交易详情。

interface MyInterface {}

static class ImplA implements MyInterface {}

static class ImplB implements MyInterface {}

class OuterTests {

   @ParameterizedTest
   @MethodSource("myInterfaceProvider")
   void test(MyInterface myInterface) {}

   static Stream<MyInterface> myInterfaceProvider() {
      return Stream.of(new ImplA(), new ImplB());
   }

   @Nested
   class InnerTests{

        @Test
        void nestedTest() {
            //how to access myInterface:MyInterface?
       }

   }

}

但仅显示包含电子邮件的行,而其他详细信息则不会显示。

电子邮件位于每个交易明细的最后一行。

bool writeNextLine = false;
StringBuilder sb = new StringBuilder();

// Read the file and display it line by line.              
using (System.IO.StreamReader file = new System.IO.StreamReader("record.txt"))
{
    while ((line = file.ReadLine()) != null)
    {
        if (line.Contains(txt_SearchBooking.Text))
        {
            // This append the text and a newline into the StringBuilder buffer       
            sb.AppendLine(line.ToString());

            lbl_result.Text += sb.ToString();
        }
    }
}

这是写入文本文件的数据。

1 个答案:

答案 0 :(得分:0)

如果每个事务总是有9行,而电子邮件是最后一行,则可以使用File.ReadAllLines和一个计数器。

var lines = File.ReadAllLines("records.txt");
for(int i = 0; i < lines.Length; i++)
{
   var line = lines[i];
   if(line.Contains(txt_SearchBooking.Text))
   {
       //Retrieve the previous lines
       for(int y = i-8; y <= i; y++)
       {               
           lbl_result.Text += lines[y];
       }
   }
}
相关问题