我想使用按钮,让用户选择一个他们希望将文件从以下扩展名移动的文件夹:.shp,.dbf和.shx,到将这些文件移动一组后创建的文件夹名称(即出口)。
编辑*
好的,这是我想出的:
Private Sub SelectFolder_Click(sender As Object, e As EventArgs) Handles SelectFolder.Click
If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
lstFiles(FolderBrowserDialog1.SelectedPath)
End If
End Sub
Private Sub ListFiles(ByVal folderPath As String)
lstFiles.Items.Clear()
Dim fileNames = My.Computer.FileSystem.GetFiles(
folderPath, FileIO.SearchOption.SearchTopLevelOnly, "*.shp", "*.shx", "*.dbf")
For Each fileName As String In fileNames
lstfiles.Items.Add(fileName)
Next
End Sub
我是否在以正确的方式考虑这个问题?
这里有一些提示:
要从目录中获取特定的文件类型,可以执行以下操作:
Imports System.IO
'...
Dim tar = {".shp", ".shx", ".dbf"}
Dim files = Directory.EnumerateFiles(folderPath, "*.*", SearchOption.TopDirectoryOnly).
Where(Function(x) tar.Contains(Path.GetExtension(x).ToLower)).
Select(Function(x) New FileInfo(x))
或使用RegExp:
Imports System.IO
Imports System.Text.RegularExpressions
'...
Dim pattern = "^.*?(\.dbf|\.shp|\.shx)$"
Dim files = Directory.EnumerateFiles(folderPath, "*.*", SearchOption.TopDirectoryOnly).
Where(Function(x) Regex.IsMatch(x, pattern, RegexOptions.IgnoreCase)).
Select(Function(x) New FileInfo(x))
要显示files
的ListBox
:
lstFiles.DataSource = Nothing
'Or FullName to display the path.
lstFiles.DisplayMember = "Name"
lstFiles.DataSource = files.ToList
现在将这些文件复制到另一个文件夹并添加前缀/后缀:
Dim files = DirectCast(lstFiles.DataSource, List(Of FileInfo))
Dim dest As String = "DestinationPath"
Dim postfix As String = "Exports"
If Not Directory.Exists(dest) Then
Directory.CreateDirectory(dest)
End If
files.ForEach(Sub(x)
x.CopyTo(Path.Combine(dest,
$"{Path.GetFileNameWithoutExtension(x.Name)}_{postfix}{x.Extension}"),
True)
End Sub)
仅此而已。
谢谢,所有这些都能顺畅进行。还有一个问题,我可能会误会,但是如何为这些文件移动到“目标路径”定义?这是最好的方法吗?
Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RbtnBrowse.Click FolderBrowserDialog1.SelectedPath = "C:\" FolderBrowserDialog1.Description = "Select A Destination Folder" If FolderBrowserDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then txtPath.Text = FolderBrowserDialog1.SelectedPath End If End Sub
是。如果要允许用户指定目的地,请使用这种方式。否则,只需对其进行硬编码即可。即
dest = "c:\MyTmpFolder"