Проблемы с разрешениями при копировании каталогов

Мне нужна помощь с моим кодом, я создал программу Visual Basic, которая копирует файлы и каталоги с локального диска в общий сетевой ресурс, но я все время получаю сообщение об ошибке доступа к пути C:\Users\*username*\Documents\My Music запрещена. Хотя у меня нет подкаталога My Music в каталоге Documents. Любая помощь будет оценена по достоинству. Вот мой код ниже:

Imports System.IO

Public Class Choices
 Private Sub Choices_Load(sender As Object, e As EventArgs) Handles MyBase.Load
 End Sub

 Public Sub btnDocuments_Click(sender As Object, e As EventArgs) Handles btnDocuments.Click
 Dim docsDirectory, destdocsDirectory, userDirectory, userName, hDrive, mydocsDirectory, destmydocsDirectory As String
 'Function to pull user profile path
 hDrive = Environment.GetEnvironmentVariable("homedrive")
 userName = Environment.GetEnvironmentVariable("username")
 userDirectory = Environment.GetEnvironmentVariable("userprofile")
 docsDirectory = userDirectory + "\Documents"
 destdocsDirectory = hDrive + userName + "\My Files"
 mydocsDirectory = "C:\My Documents"
 destmydocsDirectory = hDrive + userName + "\My Documents"

 'Used for error checking
 'MessageBox.Show(sourceDirectory + vbCrLf + destDirectory)

 If (My.Computer.FileSystem.DirectoryExists(destdocsDirectory)) Then
 For Each foundFile As String In My.Computer.FileSystem.GetFiles(docsDirectory, _
 FileIO.SearchOption.SearchAllSubDirectories, "*.*")
 Select Case LCase(Path.GetExtension(foundFile))
 Case ".mks"
 Case ".wav"
 Case ".jpg"
 Case ".wmv"
 Case ".lnk"
 Case ".png"
 Case ".exe"
 Case ".jpeg"
 Case ".dll"
 Case ".msi"
 Case ".bmp"
 Case ".url"
 Case ".log"
 Case ".dat"
 Case ".ini"
 Case ".propdesc"
 Case ".arx"
 Case ".hdi"
 Case ".mc3"
 Case ".css"
 Case ".gif"
 Case ".tif"
 Case ".tiff"
 Case ".htm"
 Case ".chm"
 Case ".pc3"
 Case ".mp3"
 Case ".mp4"
 Case Else
 My.Computer.FileSystem.CopyFile(foundFile, destdocsDirectory & "\" & Path.GetFileName(foundFile), showUI:=FileIO.UIOption.AllDialogs)
 End Select
 Next
 Else
 My.Computer.FileSystem.CreateDirectory(destdocsDirectory)
 For Each foundFile As String In My.Computer.FileSystem.GetFiles(docsDirectory, _
 FileIO.SearchOption.SearchAllSubDirectories, "*.*")
 Select Case LCase(Path.GetExtension(foundFile))
 Case ".mks"
 Case ".wav"
 Case ".jpg"
 Case ".wmv"
 Case ".lnk"
 Case ".png"
 Case ".exe"
 Case ".jpeg"
 Case ".dll"
 Case ".msi"
 Case ".bmp"
 Case ".url"
 Case ".log"
 Case ".dat"
 Case ".ini"
 Case ".propdesc"
 Case ".arx"
 Case ".hdi"
 Case ".mc3"
 Case ".css"
 Case ".gif"
 Case ".tif"
 Case ".tiff"
 Case ".htm"
 Case ".chm"
 Case ".pc3"
 Case ".mp3"
 Case ".mp4"
 Case Else
 My.Computer.FileSystem.CopyFile(foundFile, destdocsDirectory & "\" & Path.GetFileName(foundFile), showUI:=FileIO.UIOption.AllDialogs)
 End Select
 Next
 End If

 If (My.Computer.FileSystem.DirectoryExists(mydocsDirectory)) Then
 For Each foundFile As String In My.Computer.FileSystem.GetFiles(mydocsDirectory, _
 FileIO.SearchOption.SearchAllSubDirectories, "*.*")
 Select Case LCase(Path.GetExtension(foundFile))
 Case ".mks"
 Case ".wav"
 Case ".jpg"
 Case ".wmv"
 Case ".lnk"
 Case ".png"
 Case ".exe"
 Case ".jpeg"
 Case ".dll"
 Case ".msi"
 Case ".bmp"
 Case ".url"
 Case ".log"
 Case ".dat"
 Case ".ini"
 Case ".propdesc"
 Case ".arx"
 Case ".hdi"
 Case ".mc3"
 Case ".css"
 Case ".gif"
 Case ".tif"
 Case ".tiff"
 Case ".htm"
 Case ".chm"
 Case ".pc3"
 Case "."
 Case Else
 My.Computer.FileSystem.CopyFile(foundFile, destmydocsDirectory & "\" & Path.GetFileName(foundFile), showUI:=FileIO.UIOption.AllDialogs)
 End Select
 Next
 Else
 MessageBox.Show(mydocsDirectory + "Does not exist")
 End If
 End Sub

 Private Sub btnDesktop_Click(sender As Object, e As EventArgs) Handles btnDesktop.Click
 Dim deskDirectory, destdeskDirectory, userDirectory, userName, hDrive As String
 hDrive = Environment.GetEnvironmentVariable("homedrive")
 userName = Environment.GetEnvironmentVariable("username")
 userDirectory = Environment.GetEnvironmentVariable("userprofile")
 deskDirectory = userDirectory + "\Desktop"
 destdeskDirectory = hDrive + userName + "\Desktop"
 If (My.Computer.FileSystem.DirectoryExists(deskDirectory)) Then
 For Each foundFile As String In My.Computer.FileSystem.GetFiles(deskDirectory, _
 FileIO.SearchOption.SearchAllSubDirectories, "*.*")
 Select Case LCase(Path.GetExtension(foundFile))
 Case ".mks"
 Case ".wav"
 Case ".jpg"
 Case ".wmv"
 Case ".lnk"
 Case ".png"
 Case ".exe"
 Case ".jpeg"
 Case ".dll"
 Case ".msi"
 Case ".bmp"
 Case ".url"
 Case ".log"
 Case ".dat"
 Case ".ini"
 Case ".propdesc"
 Case ".arx"
 Case ".hdi"
 Case ".mc3"
 Case ".css"
 Case ".gif"
 Case ".tif"
 Case ".tiff"
 Case ".htm"
 Case ".chm"
 Case ".pc3"
 Case "."
 Case Else
 My.Computer.FileSystem.CopyDirectory(foundFile, destdeskDirectory & "\" & Path.GetFileName(foundFile), showUI:=FileIO.UIOption.AllDialogs)
 End Select
 Next
 End If
 End Sub
End Class
1 ответ

Каталог называется Music. По каким-то волшебным окнам он отображается как " My Music. Попробуйте использовать физическое имя Music.

Аналогичная проблема существует для My Documents и Documents.

Если вам нужен каталог документов текущего пользователя, вы можете получить его с помощью

destmydocsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)

Если вы хотите получить доступ к каталогам других пользователей, вам необходимо быть администратором, иначе вы обычно не будете иметь права доступа к ним!

Вы объявили один и тот же длинный список " Select Case несколько раз. Было бы намного проще управлять, если бы вы поместили все расширения в HashSet(Of String):

Private m_mediaExtensions As New HashSet(Of String)() From { ".mks", ".wav", ... }

Затем вы можете проверить

If m_mediaExtensions.Contains(myExtension) Then
 ...
Else
 ...
End If

Примечание. В VB инициализаторы коллекции существуют с VS2010. Для более ранних версий вы можете передать перечисление конструктору:

m_mediaExtensions = New HashSet(Of String)(New String() {".mks", ".wav", ...})

UPDATE в ответ на ваш комментарий. Примечание. Я еще не исправил пути.

Imports System.IO

Public Class Choices
 Private m_mediaExtensions As HashSet(Of String) = _
 New HashSet(Of String)(New String() {".mks", ".wav", ".jpg"})

 Public Sub btnDocuments_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnDocuments.Click
 Dim docsDirectory, destdocsDirectory, userDirectory, userName, hDrive, mydocsDirectory, destmydocsDirectory As String
 'Function to pull user profile path
 hDrive = Environment.GetEnvironmentVariable("homedrive")
 userName = Environment.GetEnvironmentVariable("username")
 userDirectory = Environment.GetEnvironmentVariable("userprofile")
 docsDirectory = userDirectory + "\Documents"
 destdocsDirectory = hDrive + userName + "\My Files"
 mydocsDirectory = "C:\My Documents"
 destmydocsDirectory = hDrive + userName + "\My Documents"

 'Used for error checking
 'MessageBox.Show(sourceDirectory + vbCrLf + destDirectory)

 If Not Directory.Exists(destdocsDirectory) Then
 My.Computer.FileSystem.CreateDirectory(destdocsDirectory)
 End If
 For Each foundFile As String In My.Computer.FileSystem.GetFiles(docsDirectory, _
 FileIO.SearchOption.SearchAllSubDirectories, "*.*")
 If Not m_mediaExtensions.Contains(LCase(Path.GetExtension(foundFile))) Then
 My.Computer.FileSystem.CopyFile(foundFile, destdocsDirectory & "\" & Path.GetFileName(foundFile), showUI:=FileIO.UIOption.AllDialogs)
 End If
 Next

 If Directory.Exists(mydocsDirectory) Then
 For Each foundFile As String In My.Computer.FileSystem.GetFiles(mydocsDirectory, _
 FileIO.SearchOption.SearchAllSubDirectories, "*.*")
 If Not m_mediaExtensions.Contains(LCase(Path.GetExtension(foundFile))) Then
 My.Computer.FileSystem.CopyFile(foundFile, destmydocsDirectory & "\" & Path.GetFileName(foundFile), showUI:=FileIO.UIOption.AllDialogs)
 End If
 Next
 Else
 MessageBox.Show(mydocsDirectory + "Does not exist")
 End If
 End Sub

 Private Sub btnDesktop_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnDesktop.Click
 Dim deskDirectory, destdeskDirectory, userDirectory, userName, hDrive As String
 hDrive = Environment.GetEnvironmentVariable("homedrive")
 userName = Environment.GetEnvironmentVariable("username")
 userDirectory = Environment.GetEnvironmentVariable("userprofile")
 deskDirectory = userDirectory + "\Desktop"
 destdeskDirectory = hDrive + userName + "\Desktop"
 If Directory.Exists(deskDirectory) Then
 For Each foundFile As String In My.Computer.FileSystem.GetFiles(deskDirectory, _
 FileIO.SearchOption.SearchAllSubDirectories, "*.*")
 If Not m_mediaExtensions.Contains(LCase(Path.GetExtension(foundFile))) Then
 My.Computer.FileSystem.CopyDirectory(foundFile, destdeskDirectory & "\" & Path.GetFileName(foundFile), showUI:=FileIO.UIOption.AllDialogs)
 End If
 Next
 End If
 End Sub
End Class

licensed under cc by-sa 3.0 with attribution.