Deleting Specific Files and then Extract them into another folder - vb.net

With the following code I am trying to delete specific files inside of a folder on a flash drive, and then copy the remaining files into a separate folder. When the program runs and I initiate the button to do so, the program deletes files that have not been modified within the past year, but then it does not continue to extract the remaining files and place them into a separate folder.
Does anyone know why?
Imports System.IO
Public Class frmExtractionator
Dim txtFiles1 As Control
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
DeleteUnmodifiedFiles(sourceDirectory, 365)
Dim txtFiles = Directory.EnumerateFiles(sourceDirectory)
If (Not System.IO.Directory.Exists(archiveDirectory)) Then
System.IO.Directory.CreateDirectory(archiveDirectory)
End If
For Each currentFileLoc As String In txtFiles
Dim fileName = currentFileLoc.Substring(sourceDirectory.Length + 1)
File.Move(currentFileLoc, Path.Combine(archiveDirectory, fileName))
Next
Catch eT As Exception
Console.WriteLine(eT.Message)
End Try
End Sub
Private Sub DeleteUnmodifiedFiles(ByVal directoryName As String, ByVal 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
MessageBox.Show("Deleting Files")
End Sub
End Class

This will delete any file in the source directory that hasn't been modified for a year, and then will move any remaining files to the destination directory...
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
Dim fileListA() As String
fileListA = (IO.Directory.GetFiles("C:\Scource_Directory"))
For Each i As String In fileListA
If (IO.File.GetLastWriteTime(i).ToShortDateString.Substring(6)) < (CType(DateTime.Now.Year.ToString, Integer) - 1) Then
IO.File.Delete(i)
End If
Next
Dim fileListB() As String
fileListB = (IO.Directory.GetFiles("C:\Scource_Directory"))
For Each i As String In fileListB
IO.File.Move(i, "Destination_Directory")
Next
End Sub

Related

how to prefix filenames recursively and output to a folder

right this one is driving me mental. I'm sure I'm doing something unbelievably stupid but I can't work it out. I'm trying to copy every file within a directory structure and rename it with it's source directory, output into a single folder. my code seems to do nothing. Help!!!
Imports System.IO
Public Class Form1
Dim projDirectory As String = "C:\Users\phil\Desktop\satdoc software trial folders\test project folder"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim ProjArray = IO.Directory.GetDirectories(projDirectory)
ComboBox1.MaxDropDownItems = ProjArray.Length
For Each proj As String In ProjArray
proj = proj.Substring(proj.LastIndexOf("\") + 1)
ComboBox1.Items.Add(proj) 'populate combobox with list of projects in folder
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim projfolder As New DirectoryInfo(projDirectory & "\" & ComboBox1.SelectedItem)
finalise(projfolder)
End Sub
Private Sub finalise(ByVal folder As DirectoryInfo)
Try
Dim files = folder.GetFiles
For Each file In files
Dim pos1 = InStr(file.Name, ComboBox1.SelectedItem) - 1 'position in string marks beginning of project name
Dim pos2 = file.Name.LastIndexOf("\") ' position in string marks last subfolder
Dim NoofChars As Integer = pos2 - pos1 'number of chars to use from full string
Dim filenameappend = file.Name.Substring(pos1, NoofChars) 'select the appropriate chars
Dim append As String = filenameappend.Replace("\", " ") 'replace all teh \ with spaces
file.CopyTo(projDirectory & "\output\" & append & file.Name) 'copy to another folder and prefix the filename with the filestructure of its parent project
Label1.Text = append
Next
For Each subfolder In folder.GetDirectories
finalise(subfolder) 'recursive through all folders
Next
Catch e As Exception
End Try
End Sub
End Class

how to copy file to new directory using openfiledialog in vb.net?

I need to copy an mp3 file chosen with OpenFileDialog to a new directory. The problem is all the files inside the folder copies to the new directory. I want to copy only the specific file chosen in that folder. pls help.
note: after opening the mp3 file, Textbox1 will display the source path of the file(sourcepath). then Textbox2 will display the new path(destPath) after hitting the save button.
Private Shared Sub CopyDirectory(ByVal sourcePath As String, ByVal destPath As String)
If Not Directory.Exists(destPath) Then
Directory.CreateDirectory(destPath)
End If
For Each file__1 As String In Directory.GetFiles(Path.GetDirectoryName(sourcePath))
Dim dest As String = Path.Combine(destPath, Path.GetFileName(file__1))
File.Copy(file__1, dest)
Next
For Each folder As String In Directory.GetDirectories(Path.GetDirectoryName(sourcePath))
Dim dest As String = Path.Combine(destPath, Path.GetFileName(folder))
CopyDirectory(folder, dest)
Next
End Sub
Private Sub ButtonSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonSave.Click
Dim sourcepath As String = ""
Dim DestPath As String = "C:\Users\Big Boss Eis\Desktop\vb file maintenance\fileMaintenance with database\fileMaintenance"
sourcepath = TextBox1.Text
CopyDirectory(sourcepath, DestPath)
End Sub
Private Sub OpenFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenFile.Click
If (OpenFileDialog1.ShowDialog = DialogResult.OK) Then
AxWindowsMediaPlayer1.URL() = OpenFileDialog1.FileName
TextBox1.Text = OpenFileDialog1.FileName
End If
End Sub
Replace your entire CopyDirectory function with this
Private Shared Sub CopyDirectory(ByVal sourcePath As String, ByVal destPath As String)
If System.IO.File.Exists( sourcePath ) = True Then
System.IO.File.Copy( sourcePath , destPath )
MsgBox("File Copied")
End If
End Sub
Edited through mobile phone, excuse any errors

How to filter file names by date/time?

I need help in filtering specific time/dates(all files are in .jpeg format) in my program's report generation (motion detection system) in which the user can view detected images from a specific point of time to another (e.g. 1:00pm - 2:00pm) then display the files in the listbox.
sample screenshot filename: pic_HHMMss_ddMMMyyyy
The system works like this. After a motion is detected by the webcam, it automatically captures an image and save it to C:\Surveillance System\Detected and generate the filename pic_HHMMss_ddMMMyyyy. So this is now the report generation form wherein the authorized person can view detected images by filtering the time/date of which when the photo is captured.
For now, I can only display all the files in the directory without any filters. Any insights or help is greatly appreciated. Thanks! :)
codes:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' make a reference to a directory
Dim di As New IO.DirectoryInfo("c:\Surveillance System\Detected")
Dim diar1 As IO.FileInfo() = di.GetFiles()
Dim dra As IO.FileInfo
'list the names of all files in the specified directory
For Each dra In diar1
ListBox1.Items.Add(dra)
Next
End Sub
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
PictureBox1.Image = Image.FromFile("C:\Surveillance System\Detected\" & ListBox1.Text)
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
DateTimePicker2.Format = DateTimePickerFormat.Time
DateTimePicker2.ShowUpDown = True
DateTimePicker1.Format = DateTimePickerFormat.Time
DateTimePicker1.ShowUpDown = True
End Sub
button1_click = show detected
button2_click = clear items
There are two ways to do this. One is by the time listed as part of the file name:
Function GetFiles(ByVal FilterStart As DateTime, ByVal FilterEnd As DateTime) As IEnumerable(Of String)
Dim culture As CultureInfo = CultureInfo.InvariantCulture
Dim FormatString As String = "HHmmss_ddMMMyyyy"
Return Directory.EnumerateFiles("c:\Surveillance System\Detected") _
.Where(Function(f)
Dim Filedate As DateTime = DateTime.ParseExact(f.Replace("pic_", "").Replace(".jpeg", ""), FormatString, culture)
Return Filedate >= FilterStart AndAlso Filedate <= FilterEnd
End Function)
End Function
Update:
I see you changed the picture. The format string provided here only supports original file name format used in the original picture. The new picture shows multiple conventions for the file name format. If you are really going to have multiple kinds of names for your files, you should consider using the Created Date option below, or extend this option to use the TryParseExact() overload that accepts an array of possible formats.
The other is to use the Created Date information from the file system:
Function GetFiles(ByVal FilterStart As DateTime, ByVal FilterEnd As DateTime) As IEnumerable(Of String)
Dim di As New DirectoryInfo("c:\Surveillance System\Detected")
Return di.EnumerateFileSystemInfos() _
.Where(Function(f) f.CreationTime >= FilterStart AndAlso f.CreationTime <= FilterEnd) _
.Select(Function(f) f.Name)
End Function
Try using GetAttributes on your files
see http://msdn.microsoft.com/en-us/library/system.io.file.getattributes(v=vs.110).aspx
EDIT
This will add files created between the two times you set in your DateTimePicker. This will work if you want filter on when the file was created, otherwise you need to do some text transformations to dra.FileName to match it to your filenames. You would also want to add an event to track changes in the DateTimePickers so your list will automatically filter and update
'list the names of all files in the specified directory
For Each dra In diar1
If dra.CreationTime > DateTimePicker1.Value And dra.CreationTime < DateTimePicker2.Value Then
ListBox1.Items.Add(dra)
End If
Next
If you want use the filename then you need to the extract date and convert the text to date so you can file based on the DateTimePicker
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
DateTimePicker_ValueChanged(sender,Nothing)
End Sub
Private Sub DateTimePicker_ValueChanged(sender As System.Object, e As System.EventArgs) Handles DateTimePicker1.ValueChanged, DateTimePicker2.ValueChanged
Dim di As New IO.DirectoryInfo("c:\Surveillance System\Detected")
Dim diar1 As IO.FileInfo() = di.GetFiles()
Dim dra As IO.FileInfo
ListBox1.Items.Clear()
'list the names of all files in the specified directory
For Each dra In diar1
'Get file name and then convert to time
Dim splitname As String() = Replace(dra.Name.ToString, ".jpeg", "").Split("_")
Dim filetime As DateTime = Date.ParseExact(splitname(2) & splitname(1), "ddMMMyyyyHHmmss", System.Globalization.DateTimeFormatInfo.InvariantInfo)
If filetime > DateTimePicker1.Value And filetime < DateTimePicker2.Value Then
ListBox1.Items.Add(dra)
End If
Next
end Sub

GetDirectory will not list all Directories

I have a form that allows you to click a button, which triggers an OpenFileDialog. From there, you are suppose to select a specific file within that folder, and then the program is supposed to go through from the folder you were in the the /subjects folder and list those directories.
At the moment, I have 3 directories within /subjects: english, mathematics, and cte.
My issue is that when the program is ran, it will only list the English directory in the combo-box, and will not list any of the others.
Private Sub btnDocumentChoice_Click(sender As Object, e As EventArgs) Handles btnDocumentChoice.Click
Dim ofd As New OpenFileDialog
Dim DirList As New ArrayList
If ofd.ShowDialog = Windows.Forms.DialogResult.OK AndAlso ofd.FileName <> "" Then
strRootLocation = (Path.GetDirectoryName(ofd.FileName))
GetDirectories(strRootLocation + "/subject/", DirList)
'MessageBox.Show(Path.GetDirectoryName(ofd.FileName))
End If
End Sub
Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
strRootLocation = OpenFileDialog1.FileName
cmbSubject.Items.Add(strRootLocation)
End Sub
Sub GetDirectories(ByVal StartPath As String, ByRef DirectoryList As ArrayList)
Dim Dirs() As String = Directory.GetDirectories(StartPath)
DirectoryList.AddRange(Dirs)
For Each Dir As String In Dirs
GetDirectories(Dir, DirectoryList)
cmbSubject.Items.Add(Replace(Path.GetDirectoryName(Dir), strRootLocation + "\subject", ""))
cmbSubject.Items.Remove("")
Next
End Sub
I managed to fix my own issue by removing the For Each loop in the question, and replacing it with this:
Dim directories As String
For Each directories In Directory.GetDirectories(strRootLocation + "\subject")
cmbSubject.Items.Add(Replace(directories, strRootLocation + "\subject\", ""))
Next

Open Excel Workbook from ComboBox (VB.NET)

How to open an excel workbook from combobox?
I am using following code to populate combobox with excel filenames,
Dim files() As String
files = Directory.GetFiles("C:\Files\Folder", "*.xlsx", SearchOption.AllDirectories)
For Each FileName As String In files
ComboBox1.Items.Add(FileName.Substring(FileName.LastIndexOf("\") + 1, FileName.Length - FileName.LastIndexOf("\") - 1))
Next
But I do not have any idea about how to open the selected file.
Imports System
Imports System.IO
Imports System.Collections
Public Class Form1
Private Const TargetDir = "C:\Files\Folder"
Private FullFileList As List(Of String)
Private Sub ProcessFile(ByVal fn As String)
If Path.GetExtension(fn).ToLower = ".xlsx" Then
FullFileList.Add(fn)
ComboBox1.Items.Add(Path.GetFileName(fn))
End If
End Sub
Private Sub ProcessDirectory(ByVal targetDirectory As String)
Dim fileEntries As String() = Directory.GetFiles(targetDirectory)
Dim fileName As String
For Each fileName In fileEntries
ProcessFile(fileName)
Next fileName
Dim subdirectoryEntries As String() = Directory.GetDirectories(targetDirectory)
Dim subdirectory As String
For Each subdirectory In subdirectoryEntries
ProcessDirectory(subdirectory)
Next subdirectory
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
FullFileList = New List(Of String)
ProcessDirectory(TargetDir)
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
If ComboBox1.SelectedIndex >= 0 Then
Dim prc As New System.Diagnostics.Process
Dim psi As New System.Diagnostics.ProcessStartInfo(FullFileList(ComboBox1.SelectedIndex))
psi.UseShellExecute = True
psi.WindowStyle = ProcessWindowStyle.Normal
prc.StartInfo = psi
prc.Start()
End If
End Sub
End Class
You'll need to handle an event to react to the user's selection: either a change to the selection in the ComboBox or (better) a Button click. In your event handler you can retrieve the filename from the ComboBox:
string filename = ComboBox1.SelectedItem.ToString()
Once you have the filename, you can open the file, although how you do this will depend on what you want to do with it. This answer has some information on opening Excel files in VB.NET.
Try using
Process.start("excel "+ComboBox1.SelectedItem.ToString());
on buttonclick event