最初の言い訳は、私は英語のネイティブではなく、英語でさえ私の第二言語ではないからです. 拡張子が .txt のいくつかのファイルを、たとえば F:\From などのフォルダから別のフォルダに移動したいと考えています。F:\To. VB.net を使用して、すべてのファイルを移動したくはありませんが、そのうちのいくつか (たとえば 20 または 30) を移動先フォルダー (F:\To) に残します。たとえば、120 個のテキスト ファイルがソース フォルダー (F:\From) にある場合、それらの半分を移動先フォルダー (F:\To) に移動し、残りの半分をソース フォルダー、つまり 2 つのそれぞれに残すことはできますか?フォルダー (ソースと宛先) には、同じ数のファイルが必要です。実は移動先フォルダのファイル数が変わることもあるのですが、全部ではなく一部だけ移動したいのです。ありがとうございました。
質問する
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 に答える