0

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

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.");
    }  
}
4

2 回答 2

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.");
    }  
}
于 2015-09-27T08:43:59.637 回答
0

试试下面..是供您参考的文档。

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.");
    }  
}
于 2015-09-27T08:50:05.177 回答