Deleting Specific Files in VB.NET - 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

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

Copy files with multiple search criteria

I'm trying to copy files in a directory into a new folder. The script works on one file type, but I have 6 types I need to search for. I thought I could use a bar ("|") like you can with a Regex but that didn't work. Then I tried using an array and had no luck there.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnMove.Click
Dim sourceDir As String
sourceDir = txtMovePath.Text
Dim foundFile As Object = Nothing
Dim graphicsFldr As String
graphicsFldr = sourceDir + "\Graphics\"
For Each foundFile In My.Computer.FileSystem.GetFiles(sourceDir, _
Microsoft.VisualBasic.FileIO.SearchOption.SearchTopLevelOnly, _
"*.cgm|*.eps|*.svg|*.wmf|*.jpg|*.png|*.iso")
My.Computer.FileSystem.CopyFile(foundFile, graphicsFldr & My.Computer.FileSystem.GetName(foundFile))
Next
End Sub
End Class
Module mainModule
Sub Main()
Form1.Show()
End Sub
Use this
Dim arr = {"*cgm","*.eps","*.svg","*.wmf","*.jpg","*.png","*.iso"}
For Each foundFile In My.Computer.FileSystem.GetFiles(sourceDir, _
Microsoft.VisualBasic.FileIO.SearchOption.SearchTopLevelOnly, arr)
My.Computer.FileSystem.CopyFile(foundFile, graphicsFldr & My.Computer.FileSystem.GetName(foundFile))
Next

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

vb.net can read\ open or save file because of file name issue

I’m trying to edit my code to open all files in the folder ATC (including any subdirectory’s)
If any of these files are found not to contain the text “Index…” that, that particular file is appended to include the text found in document “C:\stuff.txt” and then save the file with the changes…
The issues I'm having are with file names.
First problem is that my TARGET_FILE won’t open; second issue is that my TARGET_FILE wont save?
Can anybody help? I have marked the code with '<<----ISSUE #1 & '<<----ISSUE #2 too point out the problems.
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Get folder containing files to ellipherate through...
Dim TARGET_FILE() As String = IO.Directory.GetFiles("C:\VTS\TREADSTONE LT\ATC", "*", SearchOption.AllDirectories)
For Each file As String In TARGET_FILE
Dim sReader As New StreamReader(file)
Dim content As String = sReader.ReadToEnd()
sReader.Close()
If Text.Contains("Index...") Then
'do nothing
Else
Dim text As String = IO.File.ReadAllText(TARGET_FILE) '<<----ISSUE #1
Dim EXTRA As String = IO.File.ReadAllText("C:\STUFF.TXT")
Dim index As Integer = text.IndexOf("<Tools>")
Dim countChars As Integer
countChars = "<Tools>".Length
If index >= 0 Then
' String is in file, starting at character "<Tools>" insert text "TEST_HELLO"
text = text.Insert(index + countChars, EXTRA)
Dim Writer As System.IO.StreamWriter
Writer = New System.IO.StreamWriter(TARGET_FILE) '<<----ISSUE #2
Writer.Write(text)
Writer.Close()
'Close this program\ form...
'Me.Close()
End If
End If
Next
Me.Close()
End Sub
Dim TARGET_FILE() As String 'This represent an array of string
File.ReadAllText
and
System.IO.StreamWriter
does not receive an array of string as parameter
You should iterate your TARGETFILE array collection and do ReadAllText for every file:
For Each File As String In TARGETFILE
Dim ReadedText as string = System.IO.File.ReadAllText(File)
Dim writer As New System.IO.StreamWriter("DestinationPath")
writer.Write(ReadedText )
Write.Close()
Next