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
Related
As you can see here I block the directory called "cleo". If I have it in my folder I can't click connect. How can I check if, for example, "Cleo", "Images", "Logs" exist in browsed file. I don't think making multiple If statements would be good, is there any other way?
Private Sub connect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles connect.Click
Dim cleoPath As String
Dim filePath As String
filePath = System.IO.Path.Combine(TextBox2.Text, "gta_sa.exe")
cleoPath = System.IO.Path.Combine(TextBox2.Text, "cleo")
If File.Exists(filePath) Then
If Directory.Exists(cleoPath) Then
MsgBox("Pronasli smo cleo fajl u vasem GTA root folderu. Da se konektujete na server morate ga obrisati.")
Else
Dim p() As Process
p = Process.GetProcessesByName("samp")
If p.Count > 0 Then
MsgBox("Vec imate pokrenut SAMP - ugasite ga.")
Else
Try
Dim prozess As Process = Process.GetProcessesByName("samp")(0)
prozess.Kill()
Catch ex As Exception
End Try
My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\SAMP", "PlayerName", TextBox1.Text)
Process.Start("samp://193.192.58.55:7782")
Dim client As New TcpClient
client.Connect("193.192.58.55", 10924)
Dim sendbytes() As Byte = System.Text.Encoding.ASCII.GetBytes(TextBox1.Text)
Dim stream As NetworkStream = client.GetStream()
stream.Write(sendbytes, 0, sendbytes.Length)
End If
End If
Else
MsgBox("Da se konektujete morate locirati GTA San Andreas folder.")
End If
End Sub
End Class
You could use extension methods combined with a directoryinfo to check if any of a list of directory exists. Depending of if you just want a true/false return or if you need to process each directories (for instance, by adding a custom message with the name of the folders that prevent your application from continuing.
Public Module DirectoryInfoExt
<System.Runtime.CompilerServices.Extension()>
Public Function AnyExists(DirInfo As IO.DirectoryInfo, ParamArray Directories As String()) As Boolean
Dim MyPath As String = DirInfo.FullName.TrimEnd("\"c) & "\"
Return Directories.Any(Function(Dir) IO.Directory.Exists(MyPath & Dir))
End Function
<System.Runtime.CompilerServices.Extension()>
Public Function GetExistingDirectories(DirInfo As IO.DirectoryInfo, ParamArray Directories As String()) As IEnumerable(Of String)
Dim MyPath As String = DirInfo.FullName.TrimEnd("\"c) & "\"
Return Directories.Where(Function(Dir) IO.Directory.Exists(MyPath & Dir))
End Function
End Module
An example the boolean return.
Dim BaseDirectory As String = "C:\Games\GTA"
Dim GamePath As New DirectoryInfo(BaseDirectory)
' Will not give the specific path that exists, only a Boolean if any of theses folder are found
Dim ModsFound As Boolean = GamePath.AnyExists("Images", "Cleo", "Logs", "SomeFolder\Subfolder")
If Not ModsFound Then
'Connect
Else
' Do something
End If
An example using the list return to generate a custome message prompt stating the name of the specific folders found.
'This version gives a list instead.
Dim ModsFoundList As IEnumerable(Of String) = GamePath.GetExistingDirectories("Images", "Cleo", "Logs", "SomeFolder\Subfolder")
Dim HasMod As Boolean = ModsFoundList.Count > 0
If HasMod Then
EvilModdedUserPrompt(ModsFoundList)
Exit Sub
End If
' Here, since HasMod is false, we can proceed with connection.
' Do connection
As for the EvilModdedUserPrompt method
Public Sub EvilModdedUserPrompt(ModsFoundList As List(Of String))
Dim OutputMessage As New Text.StringBuilder
OutputMessage.AppendLine("The following mods have been detected on your system:")
For Each Moditem As String In ModsFoundList
OutputMessage.AppendFormat("- {0}", Moditem)
OutputMessage.AppendLine()
Next
MessageBox.Show(OutputMessage.ToString)
End Sub
I have some code that should take a starting directory and loop through that and all subdirectories but instead it's getting to the last subdirectory in the first branch it goes down and exits out. I know there are a bunch of these, but I can't figure out how to get past the last subdirectory. I was hoping someone could point out how to continue on through the next directory branch. (It's just checking for files older than 1 hour and emailing me and that part works fine, it just doesn't look everywhere).
Sub Main()
Dim dirList As New String("C:\Users\Test\SampleDir")
Dim lOldNames = New List(Of String)()
ListFiles(dirList, lOldNames)
If lOldNames.Count > 0 Then
sendMail(lOldNames)
End If
End Sub
Public Function ListFiles(ByVal sdirList As String, ByVal lOldNames As List(Of String))
Dim dirList As New DirectoryInfo(sdirList)
Dim fiFileList As FileInfo() = dirList.GetFiles()
Dim fiName As FileInfo
Dim bEmpty As Boolean = False
bEmpty = IsDirectoryEmpty(dirList.ToString)
If bEmpty = False Then
For Each fiName In fiFileList
If fiName.CreationTime.AddHours(1) < DateTime.Now Then
lOldNames.Add(fiName.FullName)
End If
Next fiName
End If
Dim subDirs() As DirectoryInfo = dirList.GetDirectories()
For Each subdir As DirectoryInfo In subDirs
ListFiles(subdir.FullName, lOldNames)
Next subdir
Return lOldNames
End Function
'Function to test if directory is empty
Public Function IsDirectoryEmpty(ByVal path As String) As Boolean
Return Not (Directory.EnumerateFileSystemEntries(path).Any())
End Function
Fixed and shortened the function call per Steve's comment below:
Public Function ListFiles(ByVal sdirList As String, ByVal lOldNames As List(Of String))
Dim dirList As New DirectoryInfo(sdirList)
Dim fiFileList As FileInfo() = dirList.GetFiles()
Dim dirs As String() = Directory.GetFiles(sdirList, "*", SearchOption.AllDirectories)
For Each sfile As String In dirs
If Not sfile.Contains("Software") AndAlso Not sfile.Contains("Outbound") AndAlso Not sfile.Contains("RECYCLE.BIN") AndAlso Not sfile.Contains("System Volume") Then
Dim fiName As New FileInfo(sfile)
If fiName.CreationTime.AddHours(1) < DateTime.Now Then
lOldNames.Add(fiName.FullName)
End If
End If
Next
Return lOldNames
End Function
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
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
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).