How to copy files from an encrypted drive using VB.net? - vb.net

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

Related

Move Files of certain extension types From a User Selected Folder To a New Folder

Using a button, I am attempting to allow a user to select a folder they wish to moves files from of only the following extensions: .shp, .dbf and .shx, to a folder that will be created upon moving these files with a set name (i.e. Exports).
EDIT*
Ok, here is what I have come up with:
Private Sub SelectFolder_Click(sender As Object, e As EventArgs) Handles SelectFolder.Click
If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
lstFiles(FolderBrowserDialog1.SelectedPath)
End If
End Sub
Private Sub ListFiles(ByVal folderPath As String)
lstFiles.Items.Clear()
Dim fileNames = My.Computer.FileSystem.GetFiles(
folderPath, FileIO.SearchOption.SearchTopLevelOnly, "*.shp", "*.shx", "*.dbf")
For Each fileName As String In fileNames
lstfiles.Items.Add(fileName)
Next
End Sub
Am I thinking about it this in the correct way?
Here's some tips:
To get specific file types from a directory, you can do:
Imports System.IO
'...
Dim tar = {".shp", ".shx", ".dbf"}
Dim files = Directory.EnumerateFiles(folderPath, "*.*", SearchOption.TopDirectoryOnly).
Where(Function(x) tar.Contains(Path.GetExtension(x).ToLower)).
Select(Function(x) New FileInfo(x))
Or by using the RegExp:
Imports System.IO
Imports System.Text.RegularExpressions
'...
Dim pattern = "^.*?(\.dbf|\.shp|\.shx)$"
Dim files = Directory.EnumerateFiles(folderPath, "*.*", SearchOption.TopDirectoryOnly).
Where(Function(x) Regex.IsMatch(x, pattern, RegexOptions.IgnoreCase)).
Select(Function(x) New FileInfo(x))
To show the files in a ListBox:
lstFiles.DataSource = Nothing
'Or FullName to display the path.
lstFiles.DisplayMember = "Name"
lstFiles.DataSource = files.ToList
Now to copy these files to another folder and append a prefix/postfix:
Dim files = DirectCast(lstFiles.DataSource, List(Of FileInfo))
Dim dest As String = "DestinationPath"
Dim postfix As String = "Exports"
If Not Directory.Exists(dest) Then
Directory.CreateDirectory(dest)
End If
files.ForEach(Sub(x)
x.CopyTo(Path.Combine(dest,
$"{Path.GetFileNameWithoutExtension(x.Name)}_{postfix}{x.Extension}"),
True)
End Sub)
That's it all.

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

Getting the selected file name from the vault

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

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

Avoid system Volume information folder

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