通过文本文件c#搜索方法

时间:2016-08-05 13:17:27

标签: c# wpf search

我已经创建了一个保存和加载文本文件数据的应用程序。我想要做的是搜索一个字符串,在WPF的适当位置显示该字符串以及两个字符串。 我认为它找到了正确的字符串,因为计数器正确显示,但没有任何字符串显示。这是我的搜索方法:

   public void Search(string searchTerm)
    {
        var lineCount = File.ReadLines("products.txt").Count();
        string line;
        int counter = 0;


        System.IO.StreamReader file = new System.IO.StreamReader("products.txt");

        while ((line = file.ReadLine()) != null)
        {
            if (line.Contains(searchTerm))
            { 

                break;
            }

            counter++;
        }

        textBlock.Text = counter.ToString();

        string[] allLines = File.ReadAllLines("products.txt");

        allLines[counter] = productNameBlock.Text;
        allLines[counter + 1] = customerNameBlock.Text;
        allLines[counter + 2] = firmwareBlock.Text;


    }

任何想法?

3 个答案:

答案 0 :(得分:3)

我认为你翻转了作业:

productNameBlock.Text = allLines[counter];
customerNameBlock.Text = allLines[counter + 1];
firmwareBlock.Text = allLines[counter + 2];

其次,你没有使用lineCount所以只需删除那条额外的阅读线。

答案 1 :(得分:1)

为什么不使用我在your last question中提供的搜索功能?可以轻松完成这件事。总之...

   public void Search(string searchTerm)
    {
        var allLines = File.ReadAllLines("products.txt");
        int nonMatchingLineCount = allLines.Where(line => !line.Contains(searchTerm)).Count();

        textBlock.Text = nonMatchingLines.Count().ToString();

        productNameBlock.Text = allLines[counter];
        customerNameBlock.Text = allLines[counter + 1];
        firmwareBlock.Text = allLines[counter + 2];
    }

答案 2 :(得分:1)

好像你有这个颠倒了

allLines[counter] = productNameBlock.Text;
allLines[counter + 1] = customerNameBlock.Text;
allLines[counter + 2] = firmwareBlock.Text;

如果你这样做会怎么样?

productNameBlock.Text = allLines[counter];
customerNameBlock.Text = allLines[counter + 1];
firmwareBlock.Text = allLines[counter + 2];