visual basic 2010 | continue on error (UnauthorizedAccessException) - vb.net

Just as the title says, anyone know how to get past this error? This is my first program using visual basic and can't seem to find an answer to this...
Tried
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles GetProfiles_Button.Click
For Each fileName As String In FileIO.FileSystem.GetDirectories("C:\", FileIO.SearchOption.SearchAllSubDirectories)
CheckedListBox1.Items.Add(fileName)
On Error Resume Next
Next
End Sub
End Class
And I tried
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles GetProfiles_Button.Click
Try
For Each fileName As String In FileIO.FileSystem.GetDirectories("C:\", FileIO.SearchOption.SearchAllSubDirectories)
CheckedListBox1.Items.Add(fileName)
Next
Catch ex As UnauthorizedAccessException
MsgBox("Unable to access " & ex.Message)
End Try
End Sub
End Class
I think i could make a work around by creating a loop that tests each and every folder but that would be considerably more code and seems quite inefficient... Any suggestions?

You can get multiple exception on the file methods like GetFiles or GetDirectories.
Some of the possible exceptions(from)
some path (long ones- PathTooLongException) are not supported by CLR
security restrictions on folders/files
junctions/hard links that introduce duplicates (and in theory cycles to case StackOverflow in recursive iteration).
basic sharing violation restrictions (if you try to read files).
You have to iterate all files and folders manually:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim allCFileName = FindAllFiles("C:\")
For Each fileName As String In allCFileName
CheckedListBox1.Items.Add(fileName)
Next
End Sub
Public Shared Function FindAllFiles(rootDir As String) As String()
Dim paths = New Queue(Of String)()
Dim fileNames = New List(Of String)()
paths.Enqueue(rootDir)
While paths.Count > 0
Dim dir = paths.Dequeue()
Try
Dim files = Directory.GetFiles(dir)
For Each file As String In Directory.GetFiles(dir)
fileNames.Add(file)
Next
For Each subDir As String In Directory.GetDirectories(dir)
paths.Enqueue(subDir)
Next
Catch unauthorizedAccessException As UnauthorizedAccessException
' log the exception or ignore it
Console.WriteLine("Directory {0} could not be accessed!", dir)
Catch generalException As Exception
' log the exception or ...
Throw
End Try
End While
Return fileNames.ToArray()
End Function

Try
For Each path As String In filePath
If File.Exists(path) Then
' This path is a file
ProcessFile(path)
ElseIf Directory.Exists(path) Then
' This path is a directory
ProcessDirectory(path)
Else
Console.WriteLine("{0} is not a valid file or directory.", path)
End If
Next
Catch ex As UnauthorizedAccessException
MsgBox("Unable to access " & ex.Message)
End Try
Public Shared Sub ProcessDirectory(targetDirectory As String)
' Process the list of files found in the directory.
Dim fileEntries As String() = Directory.GetFiles(targetDirectory)
For Each fileName As String In fileEntries
ProcessFile(fileName)
Next
' Recurse into subdirectories of this directory.
Dim subdirectoryEntries As String() = Directory.GetDirectories(targetDirectory)
For Each subdirectory As String In subdirectoryEntries
ProcessDirectory(subdirectory)
Next
End Sub
Public Shared Sub ProcessFile(path As String)
File.Exists(path)
End Sub
This will access all the directory, subdirectories and files. Files.Exists should return false if you don't have access to the file, so you should also check on that.

Related

Copy all files in subfolders into new folder

I've been searching the net and have found a lot of posts about copying files, but I haven't had luck with copying files in subfolders. What I want to do is give a sourcePath, and a destinationPath. All files (including the ones in subfolders) will get copied into the destinatioPath. I've fiddled with lots of code but I haven't been able to get the search for subfolder to work.
Code I tried: but gives me an error on "dest" in the file copy line.
Public Sub CopyAllFiles(ByVal sourcePath As String, ByVal destPath As String)
Dim files() As String = IO.Directory.GetFiles(destPath)
For Each file As String In files
' Do work, example
Dim dest As String = Path.Combine(destPath, Path.GetFileName(file))
file.Copy(file, dest, True) ' Added True here to force the an overwrite
Next
End Sub
Code I tried but it moves the subfolder over to the desinationPath
Public Sub CopyDirectory(ByVal sourcePath As String, ByVal destinationPath As String)
Dim sourceDirectoryInfo As New System.IO.DirectoryInfo(sourcePath)
' If the destination folder don't exist then create it
If Not System.IO.Directory.Exists(destinationPath) Then
System.IO.Directory.CreateDirectory(destinationPath)
End If
Dim fileSystemInfo As System.IO.FileSystemInfo
For Each fileSystemInfo In sourceDirectoryInfo.GetFileSystemInfos
Dim destinationFileName As String =
System.IO.Path.Combine(destinationPath, fileSystemInfo.Name)
' Now check whether its a file or a folder and take action accordingly
If TypeOf fileSystemInfo Is System.IO.FileInfo Then
System.IO.File.Copy(fileSystemInfo.FullName, destinationFileName, True)
Else
' Recursively call the mothod to copy all the neste folders
CopyDirectory(fileSystemInfo.FullName, destinationFileName)
End If
Next
End Sub
I also tried this code buy it didn't give the files in the subfolders
Private Function CopyDirectory(sourcedir As String, targetdir As String, overwrite As Boolean) As List(Of String)
Dim failedCopy As List(Of String) = New List(Of String)
Directory.CreateDirectory(targetdir)
Dim files = Directory.GetFiles(sourcedir, "*.*", SearchOption.AllDirectories)
For Each file In files
Dim newfile = file.Replace(sourcedir, targetdir)
Dim fi = New FileInfo(file)
Try
fi.CopyTo(newfile, overwrite)
Catch ex As Exception
failedCopy.Add(file)
End Try
Next
Return failedCopy
End Function
This should get you fairly close
Private Sub DirTestCopyButton_Click(sender As Object, e As EventArgs) Handles DirTestCopyButton.Click
Try
CopyDirectoryContents("c:\temp\", "c:\out")
MessageBox.Show("Copy complete")
Catch ex As Exception
MessageBox.Show(String.Concat("An error occurred: ", ex.Message))
End Try
End Sub
Private Sub CopyDirectoryContents(sourcePath As String, destinationPath As String)
If Not Directory.Exists(sourcePath) Then
Return
End If
If Not Directory.Exists(destinationPath) Then
Directory.CreateDirectory(destinationPath)
End If
For Each filePathString As String In Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories)
Dim fileInfoItem As New FileInfo(filePathString)
Dim newFilePath As String = Path.Combine(destinationPath, fileInfoItem.Name)
If File.Exists(newFilePath) Then
'do something about this
Else
File.Copy(filePathString, newFilePath)
End If
Next
End Sub

'file' is a type and cannot be used as an expression Error

I want to create a encrypter which encrypt list of files using Rijndael, That's why I created a basic application with listbox which list all given files from a particular drive. Using following code:
Imports System.IO
Public Class Form1
Public Sub DirSearch(ByVal sDir As String)
Try
For Each dir As String In Directory.GetDirectories(sDir)
For Each file In Directory.GetFiles(dir, "*.pdf")
lstFilesFound.Items.Add(file)
FileToBase64(lstFilesFound.Items.Add(file))
Next
DirSearch(dir)
Next
Catch ex As Exception
Debug.WriteLine(ex.Message)
End Try
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DirSearch("c:\")
End Sub
And it work as expected but when i try to merge this code with this:
http://www.codeproject.com/Articles/12092/Encrypt-Decrypt-Files-in-VB-NET-Using-Rijndael
It gives error of
'file' is a type and cannot be used as an expression.
You are Importing a Namespace that contains a type named File. This causes a conflict in your For Each statement. This is an example of where Hungarian Notation is useful. Update your For Each statement to this:
For Each objFile In Directory.GetFiles(dir, "*.pdf")
lstFilesFound.Items.Add(objFile)
FileToBase64(lstFilesFound.Items.Add(objFile))
Next
For Each dir As String In Directory.GetDirectories(sDir)
For Each fi as File In Directory.GetFiles(dir, "*.pdf")
lstFilesFound.Items.Add(fi)
FileToBase64(lstFilesFound.Items.Add(fi))
Next
You can't pass FILE as the add() parameter because it isn't instantiated. Instead use the code above.

Deleting Specific Files in VB.NET

I am trying to figure out the code on Visual Basic after I have already extracted all files from a folder that was in a flash drive and put them in a folder on the computer. How could I have this program delete all the files that have not been modified from a previous date in the folder on the computer?
This is what I have so far:
Imports System.IO
Public Class frmExtractionator
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
Dim sourceDirectory As String = "E:\CopierFolderforTestDriveCapstone"
Dim archiveDirectory As String = "E:\FilesExtracted"
Try
Dim txtFiles = Directory.EnumerateFiles(sourceDirectory)
If(Not System.IO.Directory.Exists(archiveDirectory )) Then
System.IO.Directory.CreateDirectory(archiveDirectory)
End If
For Each currentFile As String In txtFiles
Dim fileName = currentFile.Substring(sourceDirectory.Length + 1)
File.Move(currentFile, Path.Combine(archiveDirectory, fileName))
Next
Catch eT As Exception
Console.WriteLine(eT.Message)
End Try
End Sub
End Class
Something like this will delete files that have not been modified since the given date.
Private Sub DeleteUnmodifiedFiles(directoryName As String, modificationThreshold As Date)
Dim folder As New DirectoryInfo(directoryName)
Dim wasModifiedSinceThreshold As Boolean
For Each file As FileInfo In folder.GetFiles
wasModifiedSinceThreshold = (file.LastWriteTime > modificationThreshold)
If (Not wasModifiedSinceThreshold) Then file.Delete()
Next
End Sub
To delete based on a number of days...
Private Sub DeleteUnmodifiedFiles(directoryName As String, modificationThresholdDays As Integer)
Dim folder As New DirectoryInfo(directoryName)
Dim thresholdDate As Date
Dim wasModifiedSinceThreshold As Boolean
For Each file As FileInfo In folder.GetFiles
thresholdDate = DateTime.Now().AddDays(-1 * modificationThresholdDays)
wasModifiedSinceThreshold = (file.LastWriteTime > thresholdDate)
If (Not wasModifiedSinceThreshold) Then file.Delete()
Next
End Sub

How to use Directory.GetFiles in VB?

I basically follow a MS example.The following is the example.
Imports System
Imports System.IO
Public Class Test
Public Shared Sub Main()
Try
' Only get files that begin with the letter "c."
Dim dirs As String() = Directory.GetFiles("c:\", "c*")
Console.WriteLine("The number of files starting with c is {0}.", dirs.Length)
Dim dir As String
For Each dir In dirs
Console.WriteLine(dir)
Next
Catch e As Exception
Console.WriteLine("The process failed: {0}", e.ToString())
End Try
End Sub
End Class
I modify a little bit, so that I can use it as file search function. However there is an error at "For Each f In Directory.GetFiles(d, FileName)". What do I do wrong?
Public Sub DirSearch(ByVal sDir As String, ByVal FileName As String)
Dim d As String
Dim f As String
Try
For Each d In Directory.GetDirectories(sDir)
For Each f In Directory.GetFiles(d, FileName)
If f = FileName Then
Form1.TextBox4.Text = "1"
Else
Form1.TextBox4.Text = "0"
End If
Next
DirSearch(d, FileName)
Next
Catch excpt As System.Exception
Debug.WriteLine(excpt.Message)
End Try
End Sub
I find this, this solve my problem
Public Sub DirSearch(ByVal sDir As String, ByVal FileName As String)
For Each foundFile As String In My.Computer.FileSystem.GetFiles(sDir, FileIO.SearchOption.SearchAllSubDirectories, FileName)
"Do the work here"
Next
End Sub

VB.NET Copy Dirs into new Dir same Path, Error "process access being used by another process."

Here Is my code
Public Sub MoveAllFolders(ByVal fromPathInfo As DirectoryInfo, ByVal toPath As String)
Dim toPathInfo = New DirectoryInfo(toPath)
If (Not toPathInfo.Exists) Then
toPathInfo.Create()
End If
'move all folders
For Each dir As DirectoryInfo In fromPathInfo.GetDirectories()
dir.MoveTo(Path.Combine(toPath, dir.Name))
Next
End Sub
MoveAllFolders("D:\Users\TheUser!\Desktop\dd", "D:\Users\TheUser!\Desktop\dd\Folders)
My goal is to move all folder inside a folder into a folder named Folders.
so If I do it on desktop all the folders in desktop will go to "Folders"
but I get an error "The process cannot access the file because it is being used by another process."
so this code can't work this way, so is there any way to do what I wanna do?
Thanks alot!
You are moving your target-directoy into itself.
You could check if the destination-path contains the source-directory's FullName.
If Not toPath.Contains(fromPathInfo.FullName) Then
dir.MoveTo(IO.Path.Combine(toPath, dir.Name))
End If
But this method would be quite hacky. Consider a folder '"D:\abc1' and a folder '"D:\abc2'. Contains would return true in this case even if the folder "abc1" and "abc2" are not the same.
This should work better:
Public Sub MoveAllFolders(ByVal fromDir As IO.DirectoryInfo, ByVal toDir As IO.DirectoryInfo, Optional ByVal excludeList As List(Of String) = Nothing)
If (Not toDir.Exists) Then
toDir.Create()
End If
'move all folders
For Each dir As IO.DirectoryInfo In fromDir.GetDirectories()
Dim targetPath = IO.Path.Combine(toDir.FullName, dir.Name)
If Not toDir.FullName = dir.FullName _
AndAlso Not IsParentDirectory(toDir, dir) _
AndAlso Not IO.Directory.Exists(targetPath) _
AndAlso (excludeList Is Nothing _
OrElse Not excludeList.Contains(dir.FullName, StringComparer.InvariantCultureIgnoreCase)) Then
Try
dir.MoveTo(targetPath)
Catch ioEx As IO.IOException
'ignore this directory'
Catch authEx As UnauthorizedAccessException
'ignore this directory'
Catch ex As Exception
Throw
End Try
End If
Next
End Sub
Public Shared Function IsParentDirectory(ByVal subDir As IO.DirectoryInfo, ByVal parentDir As IO.DirectoryInfo) As Boolean
Dim isParent As Boolean = False
While subDir.Parent IsNot Nothing
If subDir.Parent.FullName = parentDir.FullName Then
isParent = True
Exit While
Else
subDir = subDir.Parent
End If
End While
Return isParent
End Function
You could use this function in this way:
Dim excludePathList As New List(Of String)
excludePathList.Add("C:\Temp\DoNotMoveMe1\")
excludePathList.Add("C:\Temp\DoNotMoveMe2\")
MoveAllFolders(New IO.DirectoryInfo("C:\Temp\"), New IO.DirectoryInfo("C:\Temp\temp-sub\"), excludePathList)
Edit: updated according to your last comment (untested).