首页 > 解决方案 > 使用 Winforms 删除文本表单文本文件

问题描述

如何从 Winforms 中的文本文件中删除?

我的目标是从文本框中删除选定的文本,它也可以在我的文本文件中删除。

具体来说,我的需要是,如果用户从文本框中删除文本,它也会从文本文件中删除。

我的代码是:

    private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog of = new OpenFileDialog();
        of.ShowDialog();
        textBox1.Text = of.FileName;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        StreamReader sr = new StreamReader(textBox1.Text);
        textBox2.Text = sr.ReadToEnd();
        sr.Close();
    }

    private void button3_Click(object sender, EventArgs e)
    {
        StreamWriter sw = new StreamWriter(textBox1.Text, true);
        sw.WriteLine(textBox2.Text);
        sw.Close();
    }

    private void button4_Click(object sender, EventArgs e)
    {
        textBox2.SelectedText = "";
        string selectedText = "theTextYouWantToDelete";
        string fileContent = File.ReadAllText(@"C:\demo\demo.txt");
        File.WriteAllText(@"C:\demo\demo.txt", 
  fileContent.Replace(selectedText, ""));
    }

    private bool SelectedText(char arg)
    {
        throw new NotImplementedException();
    }
}

标签: c#winformstext-files

解决方案


这将用selectedText空字符串替换

string selectedText = textBox2.Text;
string fileContent = File.ReadAllText(@"C:\demo.txt");
File.WriteAllText(@"C:\demo.txt", fileContent.Replace(selectedText, ""));

推荐阅读