Reputation: 21
First excuse, since I am not an English native and even English language is not my second language. I want to move some files with .txt extension from one folder eg F:\From to another eg. F:\To. using VB.net I don't want to move all files, but some of them e.g. 20 or 30 and leave others at the destination folder (F:\To). For example, 120 text files are in the source folder (F:\From ) can I move half of them to the destination folder (F:\To), and leave other half at the source folder, that is, each of the two folders (the source and the destination) should have the same number of files. Actually, the number of files in the destination folder may change, but I want to move only some of them, not all of them. Thank You.
Upvotes: 2
Views: 4807
Reputation: 21
Thank you Mark Hurd, you helped me well. I tried the following code and it works:
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
Upvotes: 0
Reputation: 10931
You don't say which version of VB.NET. With recent versions (.NET Framework 4.0) you can do something like:
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
With older frameworks you need to use .GetFiles
instead, which, for this purpose, just has different performance characteristics, and if you're using an old VB.NET without LINQ you'd need something like:
For Each f In New DirectoryInfo("F:\From").GetFiles("*.txt")
If Not <condition selecting files> Then _
Continue For
f.MoveTo("F:\To")
Next
Upvotes: 2