1. move one folder including inside files/folders to another path. 把一個文件夾及其裏面的所有文件/文件夾移去另一個地址。
e.g.把最近一次的log文件夾SourceFolder下的所有起始位Encrypted_* 字樣的文件夾,及其這些文件夾裏的所有文件,移去收藏文件夾TargetFolder下的以當時時間命名的文件夾下。
把D:\Input\Encrypted_2020移去D:\Input\Archive\20200119_102905\Encrypted_2020
SourceFolder='D:\Input\'
TargetFolder='D:\Input\Archive\'
Dim IndividualSubFolderName As String = DateTime.Now.ToString("yyyyMMddHHmmss".Substring(0, 8)) + "_" + DateTime.Now.ToString("yyyyMMddHHmmss".Substring(8, 6))
If (Not System.IO.Directory.Exists(TargetFolder + IndividualSubFolderName)) Then
System.IO.Directory.CreateDirectory(TargetFolder + IndividualSubFolderName)
End If
Dim SubDirs() As String
Dim i As Integer
SubDirs = Directory.GetDirectories(SourceFolder, "Encrypted_*")
For i = 0 To UBound(SubDirs)
Dim Source As New DirectoryInfo(SubDirs(i))
Dim FolderName As Stringt
FolderName = Source.Name
MoveFolderTo(Source, TargetFolder + IndividualSubFolderName + "\" + FolderName)
Next
其中MoveFolderTo函數
Private Sub MoveFolderTo(ByVal fromPathInfo As DirectoryInfo, ByVal toPath As String)
Try
Directory.Move(fromPathInfo.ToString, toPath)
Catch ex As Exception
_logger.LogException(ex)
End Try
End Sub
2. 第1種情況的再舉例
把D:\bin\Encrypted_2020移去D:\Input\Encrypted_2020
SourceFolder='D:\bin\Encrypted_2020'
TargetFolder='D:\Input\'
Dim SourceEncrypt As New DirectoryInfo(SourceFolder)
Dim IndividualSubFolderName As String = SourceEncrypt.Name
If (Not System.IO.Directory.Exists(TargetFolder)) Then
System.IO.Directory.CreateDirectory(TargetFolder)
End If
MoveFolderTo(SourceEncrypt, TargetFolder + IndividualSubFolderName)
3. 刪除文件夾裏所有的某種類型的文件
e.g. 刪除fromPathInfo這個path下面所有.csv類型的文件
fromPathInfo='D:\Input\'
Private Sub DeleteAllFiles(ByVal fromPathInfo As String)
Dim OriginalFilePath = New DirectoryInfo(fromPathInfo)
Dim OriginalFilePathInfo As String
For Each file As FileInfo In OriginalFilePath.GetFiles("*.csv")
Try
OriginalFilePathInfo = fromPathInfo + "\" + file.ToString
My.Computer.FileSystem.DeleteFile(OriginalFilePathInfo)
Catch ex As Exception
_logger.LogException(ex)
End Try
Next
End Sub