从列表框和文件夹中删除选定的文件 [英] Delete Selected File from Listbox and Folder

查看:101
本文介绍了从列表框和文件夹中删除选定的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从列表框和文件夹中删除选定的文件.目前,它只是从列表框中删除它.现在,我希望也将其从文件夹"中删除.谢谢

I want to Delete the Selected File from Listbox and Folder. For now it's only removing it from the Listbox. Now I want it to be removed also from the Folder. Thanks

    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);
        }
    }

推荐答案

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

If your listBox1.Items contains your filepath, you could simply pass it by de-referencing the filepath and delete it using File.Delete like this:

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);
    }
}

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

That is, if you add your paths to the listBox1 using FullName instead of using 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名,因为无论如何它都不会更改:

If you don't want to not add the full name in the listBox1, you could also store the Folder name separately, since it will not be changed anyway:

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
    }

然后您就可以像这样使用它:

And then you just use it like this:

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);
    }
}

这篇关于从列表框和文件夹中删除选定的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆