gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:13:48 25 4
gpt4 key购买 nike

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

    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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com