[英]Delete Selected File from Listbox and Folder
我想從列表框和文件夾中刪除選定的文件。 目前,它只是從列表框中刪除它。 現在,我希望也將其從文件夾中刪除。 謝謝
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);
}
}
如果您具有訪問該文件的適當權限,則應該可以正常工作:
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
選擇了某些內容!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.