How to use Directory.GetFiles in VB? - vb.net

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

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

Blocking more folders and applications

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

visual basic 2010 | continue on error (UnauthorizedAccessException)

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.

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

Read and write into a txt file using VB.NET with words in between

I want to open a txt file and write into it numbers from 1 to 100 and put between every number enter.
One way you could try is to write the numbers into a StringBuilder and then use it's ToString() method to get the resulting text:
Imports System.IO
Imports System.Text
Public Class NumberWriter
Private ReadOnly OutputPath as String = _
Path.Combine(Application.StartupPath, "out.txt")
Public Sub WriteOut()
Dim outbuffer as New StringBuilder()
For i as integer = 1 to 100
outbuffer.AppendLine(System.Convert.ToString(i))
Next i
File.WriteAllText(OutputPath, outbuffer.ToString(), true)
End Sub
Public Shared Sub Main()
Dim writer as New NumberWriter()
Try
writer.WriteOut()
Catch ex as Exception
Console.WriteLine(ex.Message)
End Try
End Sub
End Class
There's a good example over at Home and Learn
Dim FILE_NAME As String = "C:\test2.txt"
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objWriter As New System.IO.StreamWriter(FILE_NAME)
objWriter.Write(TextBox1.Text)
objWriter.Close()
MsgBox("Text written to file")
Else
MsgBox("File Does Not Exist")
End If
You could also use the "My.Computer.FileSystem" namespace, like:
Dim str As String = ""
For num As Int16 = 1 To 100
str += num.ToString & vbCrLf
Next
My.Computer.FileSystem.WriteAllText("C:\Working\Output.txt", str, False)
See System.IO namespace, especially the System.IO.File class.