我目前有这些目录:
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.txt
移动到100
目录。对于文本文件file-101.txt
也是如此,请将其移至相关文件夹101
。
我的问题是如何编写循环以便我的程序匹配文本文件名的部分字符串并将其移动到匹配的文件夹名称?一次移动一个文件是不会有效的,因为我有数百个目录和文件来应用它。
编辑:
我对VB有点熟悉。我遇到了这个逻辑部分的问题,我想不出一种编写循环的方法,以便它可以为我传输文件。
答案 0 :(得分: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等),然后重新构建新路径。它假设目录也存在。
答案 1 :(得分: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
确保您已导入RegularExpressions。
Imports System.Text.RegularExpressions
答案 2 :(得分: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