从列表框和文件夹中删除所选文件

时间:2016-03-05 10:43:10

标签: c# xml listbox delete-file selectedindex

我想从列表框和文件夹中删除所选文件。目前它只从列表框中删除它。现在我希望它也从文件夹中删除。感谢

    private void tDeletebtn_Click(object sender, EventArgs e)

    {
        if (listBox1.SelectedIndex != -1)
            listBox1.Items.RemoveAt(listBox1.SelectedIndex);
    }

   private void TeacherForm_Load(object sender, EventArgs e)
    {
        DirectoryInfo dinfo = new DirectoryInfo(@"data\\Teachers\\");
        FileInfo[] Files = dinfo.GetFiles("*.xml");
        foreach (FileInfo file in Files)
        {
            listBox1.Items.Add(file.Name);
        }
    }

2 个答案:

答案 0 :(得分:3)

如果您的listBox1.Items包含您的文件路径,则可以通过取消引用filepath然后使用File.Delete删除它来简单地传递它:

private void tDeletebtn_Click(object sender, EventArgs e)
{
    if (listBox1.SelectedIndex != -1){
        string filepath = listBox1.Items[listBox1.SelectedIndex].ToString();
        if(File.Exists(filepath))
            File.Delete(filepath);            
        listBox1.Items.RemoveAt(listBox1.SelectedIndex);
    }
}

也就是说,如果您使用listBox1而不是使用FullName将路径添加到Name

    DirectoryInfo dinfo = new DirectoryInfo(@"data\\Teachers\\");
    FileInfo[] Files = dinfo.GetFiles("*.xml");
    foreach (FileInfo file in Files)
    {
        listBox1.Items.Add(file.FullName); //note FullName, not Name
    }

如果您不想在listBox1中添加全名,您也可以单独存储Folder名称,因为它不会被更改:

string folderName; //empty initialization
.
.
    DirectoryInfo dinfo = new DirectoryInfo(@"data\\Teachers\\");
    FileInfo[] Files = dinfo.GetFiles("*.xml");
    folderName = dinfo.FullName; //here you initialize your folder name
    //Thanks to FᴀʀʜᴀɴAɴᴀᴍ
    foreach (FileInfo file in Files)
    {
        listBox1.Items.Add(file.Name); //just add your filename here
    }

然后你就这样使用它:

private void tDeletebtn_Click(object sender, EventArgs e)
{
    if (listBox1.SelectedIndex != -1){
        //Put your folder name here..
        string filepath = Path.Combine(folderName, listBox1.Items[listBox1.SelectedIndex].ToString());
        if(File.Exists(filepath))
            File.Delete(filepath);            
        listBox1.Items.RemoveAt(listBox1.SelectedIndex);
    }
}

答案 1 :(得分:1)

如果您具有访问该文件的适当权限,则应该可以正常运行:

System.IO.File.Delete(listBox1.SelectedItem.ToString());

仅当ListBoxItem是字符串时,上述代码才适用。否则,您可以考虑将其强制转换为Data类并使用适当的属性。查看您发布的代码,不是必需的。

所以你的最终代码将是这样的:

private void tDeletebtn_Click(object sender, EventArgs e)

{
    if (listBox1.SelectedIndex != -1)
    {
        System.IO.File.Delete(listBox1.Items[listBox1.SelectedIndex].ToString());
        listBox1.Items.RemoveAt(listBox1.SelectedIndex);
    }
}

请参阅:

请确保您在ListBox中确实选择了某些内容!