I am using following code to get directory info. it works well if I search topleveldirectory.
But when i search alldirectories, it reaches system level information and throws error.
Is there any way to avoid searching system level information folder?
Thanks
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim di As New DirectoryInfo("d:\"), i As Integer
Dim aryFiles() As FileInfo = di.GetFiles("*.doc", SearchOption.TopDirectoryOnly)
For i = LBound(aryFiles) To UBound(aryFiles)
MsgBox(aryFiles(i).FullName)
Next i
End Sub
End Class
This code should do the trick for you.
Imports System.IO
Module Module1
Sub Main()
Dim folders = New DirectoryInfo("D:\").GetDirectories
Dim files = New List(Of FileInfo)
For Each folder In From d In folders Where d.Name <> "System Volume Information"
files.AddRange(folder.GetFiles("*.doc", SearchOption.TopDirectoryOnly))
Next
For Each File In files
MsgBox(File.FullName)
Next
End Sub
End Module
I'm assuming your project is .NET 3.5 or higher. Notify me if the assumption is wrong.
Edit
Since you requested for it, I hacked together code to automatically skip inaccessible folders. I did not test the code extensively so I cannot guarantee it will be bug-free.
Imports System.IO
Module Module1
Sub Main()
Dim folders = GetAllSubFolders("D:\Alex\Music")
Dim files = New List(Of FileInfo)
For Each folder In folders
files.AddRange(folder.GetFiles("*.doc", SearchOption.TopDirectoryOnly))
Next
For Each File In files
Console.WriteLine(File.FullName)
Next
Console.ReadLine()
End Sub
Function GetAllSubFolders(ByVal path As String) As IEnumerable(Of DirectoryInfo)
Dim subFolders As New List(Of DirectoryInfo)
Try
subFolders.AddRange(New DirectoryInfo(path).GetDirectories())
Catch ex As Exception
'error handling code goes here'
End Try
Dim innerSubFolders As New List(Of DirectoryInfo)
For Each folder In subFolders
innerSubFolders.AddRange(GetAllSubFolders(folder.FullName))
Next
'add the inner sub folders'
subFolders.AddRange(innerSubFolders)
'return the directories'
Return subFolders
End Function
End Module
Related
My VB.NET junk cleaner cannot delete aria-Debug-10144.log since it is used by another process.
I tried this:
Imports System.Collections.ObjectModel
Imports System.IO
Public Class Form1
Dim TempDirs As ReadOnlyCollection(Of String)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TempDirs = (My.Computer.FileSystem.GetDirectories("C:\Users\Aitor\AppData\Local\Temp"))
Dim ListDirs As List(Of String) = TempDirs.ToList
Dim directoryName As String = "C:\Users\Aitor\AppData\Local\Temp"
For Each deleteFile In Directory.GetFiles(directoryName, "*.*", SearchOption.TopDirectoryOnly)
If Not deleteFile.ToString = "aria-Debug-10144.log" Then
File.Delete(deleteFile)
End If
Next
MsgBox("Clean completed!", MsgBoxStyle.OkOnly + MsgBoxStyle.Information, "Results")
End Sub
End Class
But it still tries to do it.
Can anybody help me?
There are two reasons:
Firstly, the selected file is being occupied by another program. In this case, you need to determine whether the selected file is occupied before deleting it. Here is a small example.
Imports System.Runtime.InteropServices
Public Class Form1
<DllImport("kernel32.dll")>
Public Shared Function _lopen(ByVal lpPathName As String, ByVal iReadWrite As Integer) As IntPtr
End Function
<DllImport("kernel32.dll")>
Public Shared Function CloseHandle(ByVal hObject As IntPtr) As Boolean
End Function
Public Const OF_READWRITE As Integer = 2
Public Const OF_SHARE_DENY_NONE As Integer = &H40
Public Shared ReadOnly HFILE_ERROR As IntPtr = New IntPtr(-1)
Public Shared Function IsFileOccupied(ByVal filePath As String) As Boolean
Dim vHandle As IntPtr = _lopen(filePath, OF_READWRITE Or OF_SHARE_DENY_NONE)
CloseHandle(vHandle)
Return If(vHandle = HFILE_ERROR, True, False)
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If (IsFileOccupied("C:\Users\juliex\AppData\Local\Temp\aria-debug-13836.log")) Then
MessageBox.Show("File is already occupied")
Else
MessageBox.Show("File is not occupied")
'Then do some delete operation.
End If
End Sub
End Class
Secondly, the selected file is a temporary file and is currently locked. If you want to clear the temporary files it owns, you need to have full control to unlock these files and then delete them!
You should be very careful if you want to delete the TEMP file, whether it is owned by the application or by another owner. The original application may have applied the lock because it wanted to use the file!
At this time you can refer to this link below:
1.How can I unlock a file that is locked by a process in .NET
2.https://social.msdn.microsoft.com/Forums/vstudio/en-US/9e2044c5-ae5d-4552-a335-01cc567dfc58/how-to-unlock-a-file-used-by-other-process?forum=csharpgeneral
Here is code that works in normal folders but it does not work in the vault (solidworks epdm)
More info,if any file in any folder on my computer is selected(focused or highlighted) this code above works 100% .but I got a EPDM SolidWorks Vault folder on my C: Drive , in this vault folder the code above does not provide me with the selected item ,it gives me a blank value . No errors
Imports Shell32
Imports SHDocVw
Imports System.IO
Public Class Form1
Private Function GetExplorerSelectedFiles() As String()
Dim ExplorerFiles As New List(Of String)
Dim exShell As New Shell
For Each window As ShellBrowserWindow In DirectCast(exShell.Windows, IShellWindows)
If TryCast(window.Document, IShellFolderViewDual) IsNot Nothing Then
For Each fi As FolderItem In DirectCast(window.Document, IShellFolderViewDual).SelectedItems
ExplorerFiles.Add(fi.Name)
Next
ElseIf TryCast(window.Document, ShellFolderView) IsNot Nothing Then
For Each fi As FolderItem In DirectCast(window.Document, ShellFolderView).SelectedItems
ExplorerFiles.Add(fi.Name)
Next
End If
Next
Return ExplorerFiles.ToArray
End Function
Private Sub btntest_Click(sender As Object, e As EventArgs) Handles btntest.Click
Dim files = GetExplorerSelectedFiles()
Dim file As String = String.Join(".", files)
Label1.Text = file
End Sub
End Class
See "not working image" for more details
See "working image" for more details
I have written a small piece of code (see below) to back-up files and folders on a USB drive to the local disk. The program works fine, however after encrypting the flash drive using BitLocker. I get the following error
I should also note that the drive is accessible through Windows explorer. thanks in advance.
Imports System
Imports System.IO
Module Module1
Sub Main()
If My.Computer.Name = UCase("My-Toshiba") Then
CopyDirectory(Directory.GetCurrentDirectory(), "C:\Users\me\Documents\USB_Backup")
End If
End Sub
Private Sub CopyDirectory(ByVal sourcePath As String, ByVal destinationPath As String)
Dim sourceDirectoryInfo As New System.IO.DirectoryInfo(sourcePath)
If Not System.IO.Directory.Exists(destinationPath) Then ' If the destination folder don't exist then create it
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)
If TypeOf fileSystemInfo Is System.IO.FileInfo Then 'check whether its a file or a folder and take action accordingly
If Not System.IO.File.Exists(destinationFileName) Then
System.IO.File.Copy(fileSystemInfo.FullName, destinationFileName, True)
Else
Dim destFileInfo As New FileInfo(destinationFileName)
If fileSystemInfo.LastWriteTime > destFileInfo.LastWriteTime Then
System.IO.File.Copy(fileSystemInfo.FullName, destinationFileName, True)
End If
End If
Else
If Not System.IO.File.Exists(destinationFileName) Then
CopyDirectory(fileSystemInfo.FullName, destinationFileName) ' Recursively call the mothod to copy all the nested folders
Else
Dim destFileInfo As New FileInfo(destinationFileName)
If fileSystemInfo.LastWriteTime > destFileInfo.LastWriteTime Then
CopyDirectory(fileSystemInfo.FullName, destinationFileName)
End If
End If
End If
Next
End Sub
End Module
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.
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