.NET从列表框中删除实际文件 [英] .NET Delete actual files from listbox
问题描述
当从系统中选择该代码时,该代码旨在从系统中删除实际文件:
This code is intended to delete the actual files from the system when it is selected from the system:
Dim file As String()
file = System.IO.Directory.GetFiles("C:\Users\User\Desktop", "lalala.txt", IO.SearchOption.AllDirectories)
If ListBox1.SelectedIndex = -1 Then
MsgBox("No files selected")
Else
System.IO.File.Delete(ListBox1.Items(ListBox1.SelectedIndex).ToString())
ListBox1.Items.RemoveAt(ListBox1.SelectedIndex)
End If
但是,仅删除列表框中的项目.实际文件仍然存在.我不确定应该将file
放在Delete函数中的位置.
However, only the items in the listbox are deleted. The actual file still exists. I am unsure where I should put the file
into the Delete function.
我已经提到此,但是它没有帮助我
I have referred to this but it has not helped me.
________ UPDATE ________
我发现问题出在哪里:这是因为仅文件名被添加到了列表框中:
I have discovered where it went wrong: it is because only the file name is added to the listbox:
ListBox1.Items.Add(Path.GetFileName(fileFound))
代替Path.GetFullPath
.
无论如何,我只能使用GetFileName
删除文件吗?
Anyhow, can I delete the file with GetFileName
only?
推荐答案
最简单(最可靠)的解决方案是创建自定义数据类型,然后将其添加到ListBox
中.
The most simple (and reliable) solution would be to create a custom data type and add that to the ListBox
instead.
通过覆盖ToString()
方法,可以使它仅显示文件名,而后端对象仍包含完整路径.
By overriding the ToString()
method you can make it display only the file name, while the back-end object still contains the full path.
Public Structure FileEntry
Public FullPath As String 'A variable holding the full path to the file.
'Overriding the ToString() method, making it only return the file name.
Public Overrides Function ToString() As String
Return System.IO.Path.GetFileName(Me.FullPath)
End Function
Public Sub New(ByVal Path As String)
Me.FullPath = Path
End Sub
End Structure
现在,每当要向ListBox
添加路径时,都必须添加FileEntry
结构的新实例,而不是常规字符串:
Now whenever you want to add paths to the ListBox
you've got to add a new instance of the FileEntry
structure, instead of a regular string:
ListBox1.Items.Add(New FileEntry(fileFound))
要删除,只需将当前选定的项目转换为FileEntry
,然后将其FullPath
传递到File.Delete()
方法.
And to delete you just cast the currently selected item into a FileEntry
, and then pass its FullPath
onto the File.Delete()
method.
Dim Entry As FileEntry = DirectCast(ListBox1.Items(ListBox1.SelectedIndex), FileEntry)
System.IO.File.Delete(Entry.FullPath)
注意:,要使其正常工作,列表框中的 每个 项目必须为FileEntry
.
NOTE: For this to work every item in the list box must be a FileEntry
.
在线测试: https://dotnetfiddle.net/x2FuV3 (请原谅格式,DotNetFiddle在手机上不能很好地工作)
Online test: https://dotnetfiddle.net/x2FuV3 (pardon the formatting, DotNetFiddle doesn't work very well on a cellphone)
文档:
这篇关于.NET从列表框中删除实际文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!