【问题标题】:C# StreamReader and StreamWriter for search A word in afile?用于搜索的 C# StreamReader 和 StreamWriter 文件中的单词?
【发布时间】:2015-04-15 22:12:16
【问题描述】:

谁能帮我将多行写入文本文件,然后在该文件中搜索特定单词。我希望代码将使用 (File.Exists) 如果有的话....提前谢谢你 我的代码:

private void button1_Click(object sender, EventArgs e)
{
    int counter = 0;
    string line;



    string lines = textBox1.Text;

        StreamWriter file2 = new StreamWriter("D:\\test.txt",true);

        file2.WriteLine(lines);

        file2.Close();


    string text = textBox1.Text;

    StreamReader file3 = new StreamReader("D:\\test.txt");

    while ((line = file3.ReadLine()) != null)
    {
        if (line.Contains(text))
        {
            MessageBox.Show("Name "+text+" is Found!");
           textBox2.Text = text;

            break;
        }

        counter++;
    }

    file3.Close();

}

【问题讨论】:

  • 我可能对您的问题感到困惑,但您似乎在问题中回答了自己的问题。
  • 确实,这段代码应该可以很好地完成工作。
  • 感谢您的快速回答....问题是我无法在 textbox1 中写入多行并将它们移动到一个文件中,然后从该文件中读取文本以细化搜索到的单词并显示它在文本框2
  • 那么这个问题其实是关于一个文本框中的多行?

标签: c# file streamreader streamwriter


【解决方案1】:

谢谢大家......我终于找到了我的答案我修改了代码如下:

    private void button1_Click(object sender, EventArgs e)
    {
        int counter = 0;
        string line;

        string lines = textBox1.Text;

            StreamWriter file2 = new StreamWriter("D:\\test.txt",true);

            file2.WriteLine(lines);

            file2.Close();

        string text = textBox2.Text;

        StreamReader file3 = new StreamReader("D:\\test.txt");

        while ((line = file3.ReadToEnd()) != null)
        {
            if (line.Contains(text))
            {
                MessageBox.Show("Name "+text+" is Found!");
               textBox2.Text = text;

                break;
            }

            counter++;
        }

        file3.Close();



    }

【讨论】:

    猜你喜欢
    • 2019-02-26
    • 2012-02-22
    • 2013-05-15
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多