删除特定文件

时间:2015-09-27 08:39:01

标签: c# system.io.file

当我搜索邮政编码删除时,你能否建议一些代码,如何删除特定文件,如果我点击按钮,将删除已保存的文件。

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        string EmployeeData = File.ReadAllText("Employee.txt");
        if (EmployeeData.Contains(textDelete.Text))
        {
            System.IO.File.Delete(EmployeeData);
        }
    }
    catch
    {
        MessageBox.Show("File or path not found or invalid.");
    }  
}

2 个答案:

答案 0 :(得分:0)

只需使用以下代码即可:

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        string _path = "Employee.txt";
        string EmployeeData = File.ReadAllText(_path);
        if (EmployeeData.Contains(textDelete.Text))
        {
            System.IO.File.Delete(Path.GetFullPath(_path));
        }
    }
    catch
    {
        MessageBox.Show("File or path not found or invalid.");
    }  
}

答案 1 :(得分:0)

请尝试以下内容.. here是供您参考的文档。

private void button1_Click(object sender, EventArgs e)
{    
    try
    {
        string EmployeeData = File.ReadAllText("Employee.txt");
        if (EmployeeData.Contains(textDelete.Text))
        {
            System.IO.File.Delete(Path.GetFullPath("Employee.txt"));
        }
    }
    catch
    {
        MessageBox.Show("File or path not found or invalid.");
    }  
}

在更安全的一面,您应首先检查文件是否存在。使用File.Exists方法确保文件存在,然后才对文件执行读取/删除操作。你应该避免known exceptions。使用以下代码..

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        if (System.IO.File.Exists(Path.GetFullPath(@"Employee.txt"))
        {
            string EmployeeData = File.ReadAllText("Employee.txt");
            if (EmployeeData.Contains(textDelete.Text))
            {
                System.IO.File.Delete(Path.GetFullPath("Employee.txt"));
            }
        }
    }
    catch
    {
        MessageBox.Show("File or path not found or invalid.");
    }  
}