0

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

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

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

“我的音乐”是“我的文档”中的一个隐藏文件夹,Windows 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
4

1 回答 1

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

于 2013-07-17T11:53:04.133 回答