簡體   English   中英

通過文本文件c#的搜索方法

[英]Search Method through text file c#

我已經制作了一個可以從文本文件保存和加載數據的應用程序。 我要做的是搜索一個字符串,在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;


    }

有任何想法嗎?

我認為您已取消任務:

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

其次,您沒有使用lineCount因此只需刪除多余的閱讀行即可。

您為什么不使用我在上一個問題中提供的搜索功能? 可以輕松做到這一點。 無論如何...

   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];
    }

好像您已經扭轉了這種情況

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];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM