2012-10-04 33 views
2

第一個藉口,因爲我不是英語母語,甚至英語不是我的第二語言。 我想從一個文件夾中移動一些擴展名爲.txt的文件,例如F:\ From到另一個文件夾。 F:\要。使用VB.net 我不想移動所有文件,但其中一些例如20或30並將其他人留在目標文件夾(F:\ To)。 例如,120個文本文件位於源文件夾(F:\ From)中,我可以將其中的一半移動到目標文件夾(F:\ To),並將另一半放在源文件夾中,即每個兩個文件夾(源和目標)應具有相同數量的文件。 實際上,目標文件夾中的文件數量可能會更改,但我只想移動其中的一部分,而不是全部。 謝謝。在vb.net中移動一些具有相同擴展名的文件

回答

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 
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代替,其中,爲了這個目的,只是有不同的性能特徵較舊的框架,如果你正在使用一箇舊的VB.NET沒有LINQ,你需要這樣的東西:

For Each f In New DirectoryInfo("F:\From").GetFiles("*.txt") 
    If Not <condition selecting files> Then _ 
    Continue For 

    f.MoveTo("F:\To") 
Next 
+0

非常感謝Mark Hurd。你的回答很簡短並且重要。我會將.net幀更改爲4.0。我會嘗試使用此代碼並添加到選擇文件的條件。再次感謝你。 – Ismail

+0

好的,馬克,我用你的代碼,它工作正常,但我仍然無法插入條件,我的意思是在where-clause語法中有一個錯誤。你能再次幫助我嗎?非常感謝你 – Ismail

+0

你還沒有提到移動的條件。要麼更新您的問題,要麼更復雜,您可能需要提出一個新問題。 –

相關問題