复制文件夹和排除文件夹

时间:2013-07-17 11:28:18

标签: vb.net visual-studio

我有一个代码,可以通过文本框将文件夹复制到另一个位置。 Textbox1用户可以指定要复制的文件夹以及用户可以浏览目标文件夹的textbox2

如果Textbox1是“我的文档”的路径,则会出现错误:

  

拒绝访问路径C:\Users\%USERNAME%\Documents\My Music

“我的音乐”是“我的文档”中的一个隐藏文件夹,被Windows 7检查为“隐藏受保护的操作系统文件”。我在VB.net中使用Visual Studio 2005和新版本,任何人都可以查看这段代码并告诉我一种排除要复制的文件夹的方法吗?

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 个答案:

答案 0 :(得分:1)

我建议将问题分成4个潜艇。首先是两个子,允许用户选择他们想要的源和目的地文件夹。 a按钮单击事件开始复制,最后是实际处理复制的子。

尝试使用此尺寸:

    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好运,有时候会很烦人,但它非常有用。