c# - 从列表框和文件夹中删除选定的文件

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

最佳答案

如果您的 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);
    }
}

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

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

关于c# - 从列表框和文件夹中删除选定的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35813096/

相关文章:

html - 提取 HTML 文件中两个标签之间的数据

vb.net - 从数据表中获取值(value)

c# - 控件如何确定使用哪个 DataContext?

c# - 如何使用 dotnet(nuget 包)httpclient 配置 TCP 连接数?

c# - 将多个 WSDL 版本反序列化为同一对象

java - 应用程序在启动时以两 Pane 模式崩溃

c# - 在 ASP.NET CORE Web API 中获取客户端 IP 地址有问题吗?

javascript - 将 xml 中的数据获取到传单 map 中

c# - 如何将项目添加到列表框的顶部

python - 如何指示 urwid 列表框的项目多于当前显示的项目?