0

我目前有这些目录:

C:\testfolder\100
C:\testfolder\101
C:\testfolder\102

我在同一个目录中有这些文件:

C:\testfolder\file-100.txt
C:\testfolder\file-101.txt
C:\testfolder\file-102.txt

我在 VB 中尝试做的是将文本文件移动file-100.txt100目录中。文本文件也一样file-101.txt,将其移至其相关文件夹101

我的问题是如何编写一个循环,以便我的程序匹配我的文本文件名字符串的一部分并将其移动到匹配的文件夹名称?一次移动一个文件效率不高,因为我有数百个目录和文件可以应用它。

编辑:

我对VB有点熟悉。我在这个逻辑部分遇到了麻烦,我想不出一种方法来编写一个循环,以便它可以为我传输文件。

4

3 回答 3

0

如果没有错误检查,这将是移动这些文件的简单例程。它基于您的文件名是一致的:

Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
  Dim homePath As String = "c:\testfolder"

  Dim files() As String = Directory.GetFiles(homePath, "*.txt")
  For Each f As String In files
    Dim fileName As String = Path.GetFileName(f)

    Dim destPath As String = Path.GetFileNameWithoutExtension(fileName)
    destPath = destPath.Split("-")(1)
    destPath = Path.Combine(homePath, destPath)

    Dim destFile As String = Path.Combine(destPath, fileName)

    File.Move(f, destFile)
  Next
End Sub

这只是获取目录中的文本文件列表,解析文件名以仅获取数字值(100、101 等),然后重建新路径。它假设目录也存在。

于 2012-07-06T15:01:54.253 回答
0

您可以使用正则表达式来查找匹配的模式

    Dim dir As String = "C:\testfolder\"
    Dim fileList() As String = {"C:\testfolder\file-100.txt", _
                                "C:\testfolder\file-101.txt", _
                                "C:\testfolder\file-102.txt"}

    Dim pattern As New Regex(Replace(dir, "\", "\\") & "file-([0-9]+)[.]txt")

    For Each value As String In fileList
        Dim match As Match = pattern.Match(value)
        If match.Success Then
            MsgBox("move from " & dir & " to " & dir & match.Groups(1).Value)
        End If
    Next

确保您有导入正则表达式。

Imports System.Text.RegularExpressions
于 2012-07-06T15:08:30.857 回答
0
Private Sub organizeFiles(ByVal folderPath As String)
    For Each filePath As String In Directory.GetFiles(folderPath, "*.txt")
        Dim destinationFilePath As String = getDestinationFilePath(filePath)
        If destinationFilePath IsNot Nothing Then
            File.Move(filePath, destinationFilePath)
        End If
    Next
End Sub

Private Function getDestinationFilePath(ByVal filePath As String) As String
    Const fileNamePrefix As String = "file-"
    Dim fileName As String = Path.GetFileName(filePath)
    Dim fileNameWithoutExtension As String = Path.GetFileNameWithoutExtension(filePath)
    If Not fileNameWithoutExtension.StartsWith(fileNamePrefix) Then
        Return Nothing
    End If
    Dim folderName As String = fileNameWithoutExtension.Substring(fileNamePrefix.Length)
    Dim fileFolderPath As String = Path.GetDirectoryName(filePath)
    Dim destinationFolderPath As String = Path.Combine(fileFolderPath, folderName)
    Dim destinationFilePath As String = Path.Combine(destinationFolderPath, fileName)
    Return destinationFilePath
End Function
于 2012-07-06T15:09:45.117 回答