2013-10-09 99 views
0

我有以下代碼複製一切,除了文件1在正確的地方,文件2 &文件3.VB.Net如何通過文件夾itterate和複製文件

來源:「C:\目錄「 目標: 」C:\ tmp目錄\備份「

Public Sub CopyDirectory(source As DirectoryInfo, target As DirectoryInfo) 

    'Recursively call the DeepCopy Method for each Directory 
    For Each MyDir As DirectoryInfo In source.GetDirectories() 
     CopyDirectory(MyDir, target.CreateSubdirectory(projectName & "\" & MyDir.Name)) 
    Next 

    ' Go ahead and copy each file in "source" to the "target" directory 
    For Each MyFile As FileInfo In source.GetFiles() 

     If Not (File.Exists(Path.Combine(target.FullName, MyFile.Name))) Then 
      MyFile.CopyTo(Path.Combine(target.FullName, MyFile.Name)) 
     Else 
      MessageBox.Show("File already exist") 
     End If 

    Next 
End Sub 

文件1,2 & 3應該去裏面的 」目錄「 中的文件夾,但它不斷出現在了 」備份「 文件夾中。

C:\ 
|_ tmp 
    |_ Backup 
     |_ Dir 
      |_ Folder 1 
       |_ File 11 
       |_ File 12 
       |_ File 13 
      |_ Folder 2 
       |_ File 21 
       |_ File 22 
       |_ File 23 
      |_ Folder 3 
       |_ File 31 
       |_ File 32 
       |_ File 33 

     |_ File 1 
     |_ File 2 
     |_ File 3 

如何確保文件1,2和3被複制到「Dir」文件夾中?

+0

檢查target.CreateSubdirectory(項目名稱& 「\」 &MyDir.Name)返回DirInfo的哪個目錄 – Patel

+0

什麼是變量'projectName' ?它不在參數列表中或在您的功能中定義。它是你的類的成員變量嗎? – mortb

+0

什麼是file1,file2,file3的源文件的路徑? –

回答

0

我認爲你的問題就出在這行:

CopyDirectory(MyDir, target.CreateSubdirectory(projectName & "\" & MyDir.Name)) 

我想你想創建在目標的新文件夾。爲此,你這樣做:

CopyDirectory(MyDir, target.CreateSubdirectory(MyDir.Name)) 

Ehm right。錯過了這行:

來源: 「C:\目錄」 目標: 「C:\ tmp目錄\備份」

你的程序是做你告訴它做什麼。把目錄中的文件放入備份中。如果你想要改變,你需要在開始第一次遞歸時將目標設置爲C:\ temp \ Backup \ dir。

0

代碼被改爲如下。 謝謝WozzeC。

終極密碼:

    fullPath = Path.GetFullPath(txtSLocation1.Text).TrimEnd(Path.DirectorySeparatorChar) 
       projectName = Path.GetFileName(txtSLocation1.Text) 

       Dim SourcePath As New IO.DirectoryInfo(txtSLocation1.Text) 
       Dim DestPath As New IO.DirectoryInfo(txtDLocation1.Text & "\" & projectName) 

       DestString = txtDLocation1.Text & "\" & projectName 
       CopyDirectory(SourcePath, DestPath) 

CopyDirectory

Public Sub CopyDirectory(source As DirectoryInfo, target As DirectoryInfo) 


    If (Not System.IO.Directory.Exists(DestString)) Then 
     System.IO.Directory.CreateDirectory(DestString) 
    End If 

    'Recursively call the DeepCopy Method for each Directory 
    For Each MyDir As DirectoryInfo In source.GetDirectories() 
     CopyDirectory(MyDir, target.CreateSubdirectory(MyDir.Name)) 
    Next 

    ' Go ahead and copy each file in "source" to the "target" directory 
    For Each MyFile As FileInfo In source.GetFiles() 

     If Not (File.Exists(Path.Combine(target.FullName, MyFile.Name))) Then 
      MyFile.CopyTo(Path.Combine(target.FullName, MyFile.Name)) 
     Else 
      MessageBox.Show("File already exist") 
     End If 
    Next 
End Sub 
相關問題