2013-07-17 133 views
0

我有一個代碼,通過文本框將文件夾複製到另一個位置。 Textbox1其中用戶可以指定要複製的文件夾,並且textbox2用戶可以瀏覽目標文件夾。複製文件夾和排除文件夾

如果Textbox1是「我的文檔」發生一個錯誤說法的路徑:

訪問路徑C:\Users\%USERNAME%\Documents\My Music被拒絕。

「我的音樂」,是在「我的文檔」被選中爲一個隱藏文件夾「隱藏受保護的操作系統文件」的窗口7.我使用Visual Studio 2005和新的VB.net,任何人可以拿看看這段代碼並告訴我一種排除要複製的文件夾的方法?

Private Sub Button7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button7.Click 
    Dim fs As Object = CreateObject("Scripting.FileSystemObject") 

    Dim sFolderpath As String = TextBox1.Text 
    Dim sourceFolderName As String = System.IO.Path.GetFileName(sFolderpath) 

    Dim strDate As String = DateTime.Now.ToString("yyyy-MM-dd") 
    Dim dFolderpath As String = System.IO.Path.Combine(TextBox6.Text, strDate) 
    fs.createfolder(dFolderpath) 
    dFolderpath = System.IO.Path.Combine(dFolderpath, sourceFolderName) 
    fs.createfolder(dFolderpath) 

    fs.copyfolder(sFolderpath, dFolderpath) 
End Sub 

回答

1

我建議將問題分解爲4個子目錄。首先是兩個子目錄,允許用戶選擇他們想要的源文件夾和目標文件夾。開始複製的按鈕單擊事件,最後是實際處理複製的子事件。

試試這個關於大小:

Dim CopyFromPath As String 
Dim CopyToPath As String 

Private Sub TextBox1_MouseClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.MouseClick 
    Dim fldbroser1 As New FolderBrowserDialog 
    fldbroser1.RootFolder = Environment.SpecialFolder.MyMusic 
    fldbroser1.ShowDialog() 
    CopyFromPath = fldbroser1.SelectedPath 
End Sub 

Private Sub TextBox2_MouseClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.MouseClick 
    Dim fldbroser1 As New FolderBrowserDialog 
    fldbroser1.RootFolder = Environment.SpecialFolder.MyComputer 
    fldbroser1.ShowDialog() 
    CopyToPath = fldbroser1.SelectedPath 
End Sub 

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
    CopyAllFiles(CopyFromPath, CopyToPath) 
End Sub 

Private Sub CopyAllFiles(ByVal CopyFromPath As String, ByVal CopyToPath As String) 
    If Not Directory.Exists(CopyToPath) Then 
     Directory.CreateDirectory(CopyToPath) 
    End If 

    For Each filee As String In Directory.GetFiles(Path.GetDirectoryName(CopyFromPath)) 
     Dim dest As String = Path.Combine(CopyToPath, Path.GetFileName(filee)) 
     File.Copy(filee, dest) 
    Next 

    For Each folder As String In Directory.GetDirectories(Path.GetDirectoryName(CopyFromPath)) 
     Dim dest As String = Path.Combine(CopyToPath, Path.GetFileName(folder)) 
     CopyAllFiles(folder, dest) 
    Next 
End Sub 

您需要導入System.IO這個工作。如果您在代碼方面有問題,請隨時提出任何問題。祝你好運學習VB,它有時可能很煩人,但它非常有用。

+0

謝謝,我會盡力將其實現到我的代碼。也許你知道爲什麼windows 7在「我的文檔」中爲隱藏文件夾標準的「我的音樂」,「我的圖片」和「我的視頻」? –

+0

我看不到任何用戶擁有我的文檔/音樂等文件夾的任何理由將被隱藏。如果您嘗試將不同用戶的文件夾訪問到正在運行代碼的用戶的文件夾,則可能是此問題。我想有一種解決方法是使用安全權限,但如果我提供的代碼有效,它應該是合理的,並且用戶友好。 – FraserOfSmeg

+0

感謝您的幫助「FraserOfSmeg」,但我需要堅持原來的代碼。請看看我的另一個問題,這個問題會解釋更多關於這個問題的信息。 –