温馨提示:本文翻译自stackoverflow.com,查看原文请点击:vb.net - Move Files of certain extension types From a User Selected Folder To a New Folder
vb.net

vb.net - 将某些扩展名类型的文件从用户选择的文件夹移动到新文件夹

发布于 2020-04-06 00:31:58

我想使用按钮,让用户选择一个他们希望将文件从以下扩展名移动的文件夹:.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

我是否在以正确的方式考虑这个问题?

查看更多

提问者
RockiesSkier
被浏览
150
JQSOFT 2020-02-01 00:54

这里有一些提示:

要从目录中获取特定的文件类型,可以执行以下操作:

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))

要显示filesListBox

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)

仅此而已。