第一个借口,因为我不是英语母语,甚至英语也不是我的第二语言。我想将一些扩展名为 .txt 的文件从一个文件夹(例如 F:\From)移动到另一个文件夹,例如。F:\到。使用 VB.net 我不想移动所有文件,但其中一些文件,例如 20 或 30 个,而将其他文件留在目标文件夹 (F:\To)。例如,120个文本文件在源文件夹(F:\From)中,我可以将其中一半移到目标文件夹(F:\To),另一半留在源文件夹,即两个中的每个文件夹(源和目标)应该有相同数量的文件。实际上,目标文件夹中的文件数量可能会发生变化,但我只想移动其中的一部分,而不是全部。谢谢你。
问问题
4755 次
2 回答
2
你没有说哪个版本的 VB.NET。使用最新版本(.NET Framework 4.0),您可以执行以下操作:
Dim filesToMove = From f In New DirectoryInfo("F:\From").EnumerateFiles("*.txt") _
Where <insert condition selecting the files to move>
For Each f In filesToMove
f.MoveTo("F:\To")
Next
您需要使用较旧的框架.GetFiles
,为此目的,它具有不同的性能特征,如果您使用的是没有 LINQ 的旧 VB.NET,则需要类似:
For Each f In New DirectoryInfo("F:\From").GetFiles("*.txt")
If Not <condition selecting files> Then _
Continue For
f.MoveTo("F:\To")
Next
于 2012-10-04T08:22:20.030 回答
0
谢谢马克赫德,你帮了我很好。我尝试了以下代码并且它有效:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sourceDir = "F:\From"
Dim destinationDir = "F:\To"
' get the filenames of txt files
Dim SourceFiles = From f In Directory.GetFiles(sourceDir, "*.txt")
Dim DestinationFiles = From f In Directory.GetFiles(destinationDir, "*.txt")
'Calculate the difference in files between the two folders, and move files if the files
'in source folder are more than the files of the destination folder
Dim s As Integer
s = SourceFiles.Count - DestinationFiles.Count
'Find the remainder
Dim a = s Mod 2
'If the remainder is zero, then divide the
If a = 0 Then
Dim files = From f In Directory.GetFiles(sourceDir, "*.txt").Take(s / 2)
If Not Directory.Exists(destinationDir) Then
Directory.CreateDirectory(destinationDir)
End If
Dim n As Integer = 0
For Each f In files
File.Move(f, Path.Combine(destinationDir, Path.GetFileName(f)))
Next
Else
Dim files = From f In Directory.GetFiles(sourceDir, "*.txt").Take((s + 1) / 2)
If Not Directory.Exists(destinationDir) Then
Directory.CreateDirectory(destinationDir)
End If
Dim n As Integer = 0
For Each f In files
File.Move(f, Path.Combine(destinationDir, Path.GetFileName(f)))
Next
End If
End Sub
于 2012-10-06T07:23:01.253 回答