.NET 从列表框中删除实际文件
.NET Delete actual files from listbox
此代码旨在从系统中选择时从系统中删除实际文件:
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
放到删除函数的什么地方。
我提到了 但它对我没有帮助。
________UPDATE________
我发现哪里出错了:是因为listbox只添加了文件名:
ListBox1.Items.Add(Path.GetFileName(fileFound))
而不是 Path.GetFullPath
。
请问,我可以删除只有GetFileName
的文件吗?
您可以使用 Path.Combine。
由于您要在 C 中搜索:\Users\User\Desktop,您可以这样做来删除:
System.IO.File.Delete(Path.COmbine("C:\Users\User\Desktop",ListBox1.Items(ListBox1.SelectedIndex).ToString())
此处,"C:\Users\User\Desktop"
和所选索引的文本将合并为一个路径。
编辑:
我明白了,你想在文本框中只显示文件名,但也想从系统中删除文件但不能这样做,对吗?
你可以这样做:
放置两个列表框,当您将文件添加到列表框 1 时,将其路径放置到列表框 2,其可见性将为 False,这意味着它不会在运行时显示。
执行此操作,同时在列表框 1 中选择一个项目,使用 path.combine 通过添加具有相同索引号的列表中的文件名和路径来创建路径 。
像这样:
System.IO.File.Delete(path.combine(ListBox1.Items(ListBox1.SelectedIndex).ToString(), ListBox2.Items(ListBox1.SelectedIndex).ToString())
最简单(和可靠)的解决方案是创建自定义数据类型并将其添加到 ListBox
。
通过覆盖 ToString()
方法,您可以使其仅显示文件名,而后端对象仍包含完整路径。
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
结构的新实例,而不是常规字符串:
ListBox1.Items.Add(New FileEntry(fileFound))
要删除,您只需将当前选定的项目转换为 FileEntry
,然后将其 FullPath
传递给 File.Delete()
方法。
Dim Entry As FileEntry = DirectCast(ListBox1.Items(ListBox1.SelectedIndex), FileEntry)
System.IO.File.Delete(Entry.FullPath)
注意: 为使其工作 列表框中的每个 项目必须是FileEntry
.
在线测试: https://dotnetfiddle.net/x2FuV3(请原谅格式,DotNetFiddle 在手机上运行得不是很好)
文档:
如您所知,问题在于仅文件名的信息不足以删除文件。您还需要文件的完整路径。所以你需要一些方法来存储整个路径但只显示文件名。这也很重要,因为在不同的目录中可能有两个(或更多)同名文件。
ListBox 可以将其 Datasource
属性 设置为显示来自 "an object that implements the IList or IListSource interfaces, such as a DataSet or an Array."
的项目
然后你设置 DisplayMember
and ValueMember
属性来告诉它显示什么和给出什么作为值。
例如,我创建了一个名为 "FileItem" 的 class,它具有完整文件名的属性以及您想要显示的任何内容,用 [=36= 的实例填充了一个列表], 并告诉 ListBox1 显示它:
Imports System.IO
Public Class Form1
Class FileItem
Property FullName As String
Property DisplayedName As String
Public Sub New(filename As String)
Me.FullName = filename
Me.DisplayedName = Path.GetFileNameWithoutExtension(filename)
End Sub
End Class
Private Sub PopulateDeletionList(dir As String, filter As String)
Dim files = Directory.EnumerateFiles(dir, filter, SearchOption.AllDirectories)
Dim fileNames = files.Select(Function(s) New FileItem(s)).ToList()
Dim bs As New BindingSource With {.DataSource = fileNames}
ListBox1.DataSource = bs
ListBox1.DisplayMember = "DisplayedName"
ListBox1.ValueMember = "FullName"
End Sub
Private Sub ListBox1_Click(sender As Object, e As EventArgs) Handles ListBox1.Click
Dim lb = DirectCast(sender, ListBox)
Dim sel = lb.SelectedIndex
If sel >= 0 Then
Dim fileToDelete = CStr(lb.SelectedValue)
Dim choice = MessageBox.Show("Do you really want to delete " & fileToDelete, "Confirm file delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If choice = DialogResult.Yes Then
Try
File.Delete(fileToDelete)
lb.DataSource.RemoveAt(sel)
Catch ex As Exception
MessageBox.Show("Could not delete " & fileToDelete & " because " & ex.Message)
End Try
End If
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
PopulateDeletionList("C:\temp", "*.txt")
End Sub
End Class
已编辑 我忘记从列表框中删除项目。为此,它需要通过 BindingSource.
绑定到 DataSource
额外功能 鉴于可能有多个同名文件,您可能想在列表框项目中添加一个工具提示,以便您可以看到它是哪个目录已加入。请参阅 how to add tooltips on winform list box items 以了解只需稍作调整即可工作的实现,例如:
Dim toolTip As ToolTip = New ToolTip()
' ...
Private Sub ListBox1_MouseMove(sender As Object, e As MouseEventArgs) Handles ListBox1.MouseMove
Dim lb = DirectCast(sender, ListBox)
Dim index As Integer = lb.IndexFromPoint(e.Location)
If (index >= 0 AndAlso index < ListBox1.Items.Count) Then
Dim desiredTooltip = DirectCast(lb.Items(index), FileItem).FullName
If (toolTip.GetToolTip(lb) <> desiredTooltip) Then
toolTip.SetToolTip(lb, desiredTooltip)
End If
End If
End Sub
此代码旨在从系统中选择时从系统中删除实际文件:
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
放到删除函数的什么地方。
我提到了
________UPDATE________
我发现哪里出错了:是因为listbox只添加了文件名:
ListBox1.Items.Add(Path.GetFileName(fileFound))
而不是 Path.GetFullPath
。
请问,我可以删除只有GetFileName
的文件吗?
您可以使用 Path.Combine。
由于您要在 C 中搜索:\Users\User\Desktop,您可以这样做来删除:
System.IO.File.Delete(Path.COmbine("C:\Users\User\Desktop",ListBox1.Items(ListBox1.SelectedIndex).ToString())
此处,"C:\Users\User\Desktop"
和所选索引的文本将合并为一个路径。
编辑:
我明白了,你想在文本框中只显示文件名,但也想从系统中删除文件但不能这样做,对吗?
你可以这样做:
放置两个列表框,当您将文件添加到列表框 1 时,将其路径放置到列表框 2,其可见性将为 False,这意味着它不会在运行时显示。
执行此操作,同时在列表框 1 中选择一个项目,使用 path.combine 通过添加具有相同索引号的列表中的文件名和路径来创建路径 。
像这样:
System.IO.File.Delete(path.combine(ListBox1.Items(ListBox1.SelectedIndex).ToString(), ListBox2.Items(ListBox1.SelectedIndex).ToString())
最简单(和可靠)的解决方案是创建自定义数据类型并将其添加到 ListBox
。
通过覆盖 ToString()
方法,您可以使其仅显示文件名,而后端对象仍包含完整路径。
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
结构的新实例,而不是常规字符串:
ListBox1.Items.Add(New FileEntry(fileFound))
要删除,您只需将当前选定的项目转换为 FileEntry
,然后将其 FullPath
传递给 File.Delete()
方法。
Dim Entry As FileEntry = DirectCast(ListBox1.Items(ListBox1.SelectedIndex), FileEntry)
System.IO.File.Delete(Entry.FullPath)
注意: 为使其工作 列表框中的每个 项目必须是FileEntry
.
在线测试: https://dotnetfiddle.net/x2FuV3(请原谅格式,DotNetFiddle 在手机上运行得不是很好)
文档:
如您所知,问题在于仅文件名的信息不足以删除文件。您还需要文件的完整路径。所以你需要一些方法来存储整个路径但只显示文件名。这也很重要,因为在不同的目录中可能有两个(或更多)同名文件。
ListBox 可以将其 Datasource
属性 设置为显示来自 "an object that implements the IList or IListSource interfaces, such as a DataSet or an Array."
然后你设置 DisplayMember
and ValueMember
属性来告诉它显示什么和给出什么作为值。
例如,我创建了一个名为 "FileItem" 的 class,它具有完整文件名的属性以及您想要显示的任何内容,用 [=36= 的实例填充了一个列表], 并告诉 ListBox1 显示它:
Imports System.IO
Public Class Form1
Class FileItem
Property FullName As String
Property DisplayedName As String
Public Sub New(filename As String)
Me.FullName = filename
Me.DisplayedName = Path.GetFileNameWithoutExtension(filename)
End Sub
End Class
Private Sub PopulateDeletionList(dir As String, filter As String)
Dim files = Directory.EnumerateFiles(dir, filter, SearchOption.AllDirectories)
Dim fileNames = files.Select(Function(s) New FileItem(s)).ToList()
Dim bs As New BindingSource With {.DataSource = fileNames}
ListBox1.DataSource = bs
ListBox1.DisplayMember = "DisplayedName"
ListBox1.ValueMember = "FullName"
End Sub
Private Sub ListBox1_Click(sender As Object, e As EventArgs) Handles ListBox1.Click
Dim lb = DirectCast(sender, ListBox)
Dim sel = lb.SelectedIndex
If sel >= 0 Then
Dim fileToDelete = CStr(lb.SelectedValue)
Dim choice = MessageBox.Show("Do you really want to delete " & fileToDelete, "Confirm file delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If choice = DialogResult.Yes Then
Try
File.Delete(fileToDelete)
lb.DataSource.RemoveAt(sel)
Catch ex As Exception
MessageBox.Show("Could not delete " & fileToDelete & " because " & ex.Message)
End Try
End If
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
PopulateDeletionList("C:\temp", "*.txt")
End Sub
End Class
已编辑 我忘记从列表框中删除项目。为此,它需要通过 BindingSource.
绑定到 DataSource额外功能 鉴于可能有多个同名文件,您可能想在列表框项目中添加一个工具提示,以便您可以看到它是哪个目录已加入。请参阅 how to add tooltips on winform list box items 以了解只需稍作调整即可工作的实现,例如:
Dim toolTip As ToolTip = New ToolTip()
' ...
Private Sub ListBox1_MouseMove(sender As Object, e As MouseEventArgs) Handles ListBox1.MouseMove
Dim lb = DirectCast(sender, ListBox)
Dim index As Integer = lb.IndexFromPoint(e.Location)
If (index >= 0 AndAlso index < ListBox1.Items.Count) Then
Dim desiredTooltip = DirectCast(lb.Items(index), FileItem).FullName
If (toolTip.GetToolTip(lb) <> desiredTooltip) Then
toolTip.SetToolTip(lb, desiredTooltip)
End If
End If
End Sub