【问题标题】:Search Method through text file c#通过文本文件搜索方法c#
【发布时间】:2016-08-05 13:17:26
【问题描述】:

我制作了一个应用程序,它可以从文本文件中保存和加载数据。我想要做的是搜索一个字符串,在 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;


    }

有什么想法吗?

【问题讨论】:

  • 听起来 products.txt 应该是结构化格式,如 XML(或 SQLite),其设计目的是使查找/更改/保存数据变得容易,而无需遍历整个文本文件。
  • 您正在阅读文件中的所有行至少 3 次 - 为什么?这是非常低效的。您应该只执行一次。
  • 啊,真烦人!

标签: c# wpf search


【解决方案1】:

我认为你翻转了作业:

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

其次,您没有使用lineCount,所以只需删除多余的阅读行。

【讨论】:

  • 不,但我认为您错过了每天的咖啡。
  • 绝对!哈哈哈
【解决方案2】:

你为什么不使用我在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];
    }

【讨论】:

  • 您好,我尝试了您的方法,但由于某种原因一直出现错误,我已向您发送了一条消息。
  • 感谢您的所有帮助,但它是一个巨大的帮助!
  • @lucycopp 不用担心,我很抱歉!聊天似乎没有发送通知:(
【解决方案3】:

好像你把这个弄反了

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

【讨论】:

    猜你喜欢
    • 2015-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-05
    相关资源
    最近更新 更多