Copy files from one folder to another automatically by today's date - vb.net

I need to make a program in Visual Studio that copy files from one folder to another automatically by today's date. I've this code right here that a friends gives me but I don't know how to make it work. Could someone help me pls?
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim lvCreationTime As Date
Dim lvStr_Diretoria As String = ""
lvStr_Diretoria = "C:\"
Dim ficheiros() As String = IO.Directory.GetFiles(lvCreationTime)
For Each file As String In ficheiros
' Do work, example
lvCreationTime = IO.File.GetCreationTime(file)
'Dim text As String = IO.File.ReadAllText(file)
If DateDiff(DateInterval.Day, lvCreationTime, Now) = 0 Then
'file to comunicate
End If
Next
'
'If Not IO.File.Exists() Then
'End If

you can use the code below
Dim folderA As String = "C:\FolderA"
Dim folderB As String = "C:\FolderB"
'read all files from folderA
Dim infoDir As New DirectoryInfo(folderA)
Dim files As FileInfo() = infoDir.GetFiles()
'use linQ to filter by date; below from Now but you can specify what you want
Dim filter As List(Of FileInfo) = (From f In files Where f.CreationTime.Date.ToShortDateString() = Now.ToShortDateString() Select f).ToList()
' and here you move from folderA to folderB
For Each i In filter
My.Computer.FileSystem.MoveFile(i.FullName, folderB & "\" & i.Name)
Next

Related

How to search multiple text files in a directory for a string of text at once

I have a ListBox with a certain amount of items in it.
For each item in the ListBox a corresponding text file exists in the file directory.
I need to search each text file (based on what's in the ListBox) for a persons name. Each text file may contain the name or it may not.
I would then like a return which text file contains the name.
I have tried this as a way to search a text file: it works, but I'm not sure how to get this to repeat based on whats in a ListBox.
Dim sFileContents As String = String.Empty
If (System.IO.File.Exists((Application.StartupPath) & "\Project_Green.txt")) Then
sFileContents = (System.IO.File.ReadAllText((Application.StartupPath) & "\Project_Green.txt"))
End If
If sFileContents.Contains(TextBox4.Text) Then
MessageBox.Show("yup")
Else
MessageBox.Show("nope")
End If
Also, if it would be possible to ignore case that would be great.
If you have a bunch of files in a directory and you have their names in a ListBox, and you want to search their contents for something.
One liner query:
Imports System.IO
'...
Sub TheCaller()
Dim dir = My.Application.Info.DirectoryPath
Dim ext = ".txt" ' If the extensions are trimmed in the list.
Dim find = TextBox4.Text
Dim files = Directory.EnumerateFiles(dir).Where(Function(x) ListBox1.Items.Cast(Of String).
Any(Function(y) String.Concat(y, ext).
Equals(Path.GetFileName(x),
StringComparison.InvariantCultureIgnoreCase) AndAlso File.ReadLines(x).
Any(Function(z) z.IndexOf(find, StringComparison.InvariantCultureIgnoreCase) >= 0))).ToList
ListBox2.Items.Clear()
ListBox2.Items.AddRange(files.Select(Function(x) Path.GetFileNameWithoutExtension(x)).ToArray)
End Sub
Or if you prefer the For Each loop:
Sub Caller()
Dim dir = My.Application.Info.DirectoryPath
Dim find = TextBox4.Text
Dim files As New List(Of String)
For Each f As String In ListBox1.Items.Cast(Of String).
Select(Function(x) Path.Combine(dir, $"{x}.txt"))
If File.Exists(f) AndAlso
File.ReadLines(f).Any(Function(x) x.IndexOf(find,
StringComparison.InvariantCultureIgnoreCase) <> -1) Then
files.Add(f)
End If
Next
ListBox2.Items.Clear()
ListBox2.Items.AddRange(files.Select(Function(x) Path.GetFileNameWithoutExtension(x)).ToArray)
End Sub
Either way, the files list contains the matches if any.
Plus a pseudo-parallel async method, for the very heavy-duty name searches.
The Async Function SearchNameInTextFiles returns a named Tuple:
(FileName As String, Index As Integer)
where FileName is the file parsed and Index is the position where the first occurrence of the specified name (theName) was found.
If no matching sub-string is found, the Index value is set to -1.
The caseSensitive parameter allows to specify whether the match should be, well, case sensitive.
You can start the search from a Button.Click async handler (or similar), as shown here.
Imports System.IO
Imports System.Threading.Tasks
Private Async Sub btnSearchFiles_Click(sender As Object, e As EventArgs) Handles btnSearchFiles.Click
Dim filesPath = [Your files path]
Dim theName = textBox4.Text ' $" {textBox4.Text} " to match a whole word
Dim ext As String = ".txt" ' Or String.Empty, if extension is already included
Dim tasks = ListBox1.Items.OfType(Of String).
Select(Function(f) SearchNameInTextFiles(Path.Combine(filesPath, f & ext), theName, False)).ToList()
Await Task.WhenAll(tasks)
Dim results = tasks.Where(Function(t) t.Result.Index >= 0).Select(Function(t) t.Result).ToList()
results.ForEach(Sub(r) Console.WriteLine($"File: {r.FileName}, Position: {r.Index}"))
End Sub
Private Async Function SearchNameInTextFiles(filePath As String, nameToSearch As String, caseSensitive As Boolean) As Task(Of (FileName As String, Index As Integer))
If Not File.Exists(filePath) then Return (filePath, -1)
Using reader As StreamReader = New StreamReader(filePath)
Dim line As String = String.Empty
Dim linesLength As Integer = 0
Dim comparison = If(caseSensitive, StringComparison.CurrentCulture,
StringComparison.CurrentCultureIgnoreCase)
While Not reader.EndOfStream
line = Await reader.ReadLineAsync()
Dim position As Integer = line.IndexOf(nameToSearch, comparison)
If position > 0 Then Return (filePath, linesLength + position)
linesLength += line.Length
End While
Return (filePath, -1)
End Using
End Function
You can do these simple steps for your purpose:
First get all text files in the application's startup directory.
Then iterate over all names in the ListBox and for each one, search in all text files to find the file that contains that name.
To make the process case-insensitive, we first convert names and text file's contents to "lower case" and then compare them. Here is the full code:
Private Sub findTextFile()
'1- Get all text files in the directory
Dim myDirInfo As New IO.DirectoryInfo(Application.StartupPath)
Dim allTextFiles As IO.FileInfo() = myDirInfo.GetFiles("*.txt")
'2- Iterate over all names in the ListBox
For Each name As String In ListBox1.Items
'Open text files one-by-one and find the first text file that contains this name
Dim found As Boolean = False 'Changes to true once the name is found in a text file
Dim containingFile As String = ""
For Each file As IO.FileInfo In allTextFiles
If System.IO.File.ReadAllText(file.FullName).ToLower.Contains(name.ToLower) Then 'compares case-insensitive
found = True
containingFile = file.FullName
Exit For
End If
Next
'Found?
If found Then
MsgBox("The name '" + name + "' found in:" + vbNewLine + containingFile)
Else
MsgBox("The name '" + name + "' does not exist in any text file.")
End If
Next
End Sub

Item pairing between two .txt

I have been trying to combine or pair two text files.
One file contains User:Key
The other file contains Key:Pass
I want a 3rd text file created containing the corresponding pairs of User:Pass based on the key matching.
Here is what Ive tried most recently
Private Sub Rotate()
Dim Cracked() As String = IO.File.ReadAllLines(TextBox1.Text)
For Each lineA In Cracked
TextBox5.Text = lineA
check()
Next
End Sub
Private Sub check()
Dim toCheck() As String = TextBox5.Text.Split(":")
Dim tHash As String = toCheck(0)
Dim tPass As String = toCheck(1)
Dim lines1() As String = IO.File.ReadAllLines(TextBox2.Text)
For Each line In lines1
If lines1.Contains(tHash) Then
Dim toAdd() As String = line.Split(":")
Dim uHash As String = toCheck(0)
Dim uUser As String = toCheck(1)
ListBox1.Items.Add(uUser + ":" + tPass)
End If
Next
End Sub
Public Sub CopyListBoxToClipboard(ByVal ListBox2 As ListBox)
Dim buffer As New StringBuilder
For i As Integer = 0 To ListBox1.Items.Count - 1
buffer.Append(ListBox1.Items(i).ToString)
buffer.Append(vbCrLf)
Next
My.Computer.Clipboard.SetText(buffer.ToString)
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
CopyListBoxToClipboard(ListBox1)
End Sub
The delimiter changes but for now the : works.
I tried splitting and matching but either the textbox5 does not rotate or it rotates through the list and thats all.
Something like this?
Dim KeyPassFile As String = "..."
Dim UserKeyFile As String = "..."
Dim UserPassFile As String = "..."
Dim KeyPass As New Hashtable
' Read Key:Pass file
For Each Line In IO.File.ReadAllLines(KeyPassFile)
Dim iStart = Line.IndexOf(":")
Dim Key = Line.Substring(0, iStart)
Dim Pass = Line.Substring(iStart + 1)
KeyPass.Add(Key, Pass)
Next
' Create User:Pass file
Dim OutFile = IO.File.CreateText(UserPassFile)
' Read User:Key file
For Each Line In IO.File.ReadAllLines(UserKeyFile)
Dim iStart = Line.IndexOf(":")
Dim User = Line.Substring(0, iStart)
Dim Key = Line.Substring(iStart + 1)
If KeyPass.ContainsKey(Key) Then
' We have a match for the key, write it to the file
OutFile.WriteLine(User & ":" & KeyPass(Key))
End If
Next
OutFile.Close()
This will probably not work for very large files that doesn't fit in memory, and there is no duplicate check for the key insertion in the hashtable, but I'll leave something for you to do.. :)
Also, in your code, you read the file specified in the TextBox2.Text as many times as there are lines in the TextBox1.Text file..

Parse String to Date from a filename variable

Purpose is to move files in their specified folders, from which they were in IF the date is at least a day old from today. I'm having some trouble moving the file since I don't see it archived. I'm assuming it's parsing the date from a filename. VS2005 .Net 2.0
Sub CopytoArchive(ByVal mydirpath)
'mydirpath = "C:\UTResults\"
'T:\UTResults\Press3\sv70206655\data07012015.txt is an example of txtFileList
Dim txtFileList As String() = Directory.GetFiles(mydirpath, "*.txt", SearchOption.AllDirectories) 'Search all files in the given path with .txt type
For Each txtName As String In txtFileList
Dim pressname As String = txtName.Substring(0, txtName.LastIndexOf("\")) 'take out the file extension
pressname = pressname.Substring(0, pressname.LastIndexOf("\")) 'take out the folder after the press folder for a clean "PRESS" look
pressname = pressname.Remove(0, 13)
Dim folderexists As String = Path.Combine("C:\writetest\", pressname)
Dim filename = txtName.Remove(0, 4)
filename = filename.Substring(0, filename.LastIndexOf("."))
filename = Convert.ToDateTime(filename)
If filename < Date.Now Then
If My.Computer.FileSystem.DirectoryExists(folderexists) Then
My.Computer.FileSystem.MoveFile(txtName, folderexists)
Else
My.Computer.FileSystem.CreateDirectory(folderexists)
My.Computer.FileSystem.MoveFile(txtName, folderexists)
End If
End If
Next
End Sub
Sub CopytoArchive(ByVal mydirpath As String)
'mydirpath = "C:\UTResults\"
'T:\UTResults\Press3\sv70206655\data07012015.txt is an example of txtFileList
Dim dir As New DirectoryInfo(mydirpath)
Dim fileInfos = dir.EnumerateFiles("*.txt", SearchOption.AllDirectories)
fileInfos = fileInfos.
Where(Function(fi) DateTime.ParseExact(RegEx.Replace(fi.Name, "[^0-9]", ""), "MMddyyyy", Nothing) < DateTime.Now.AddDays(-1))
'The magic is here ------^^^
For Each info In fileInfos
Dim pressname As String = _
Path.GetDirectoryName(info.DirectoryName).Replace(mydirpath, "C:\writetest\")
'Better/more efficient to just call CreateDirectory() every time
My.Computer.FileSystem.CreateDirectory(pressname)
My.Computer.FileSystem.MoveFile(info.FullName, pressname)
Next
End Sub
Date strings are usually a problem, here is basic approach:
Dim s As String = "data07012015.txt"
s = s.Substring(4)
s = s.Substring(0, s.LastIndexOf("."))
' convert to valid en date string
s = s.Insert(2, "/").Insert(5, "/")
Dim dt As Date = s
If dt < Now.AddDays(-1) Then
Stop
Else
Stop
End If

VB 2010 compare string within directory and store latest revision letter of the file name

My application currently extracts data from an excel document, putting the data into a listview. I then am able to open each of the strings/items within the listview (which are pdf files in a given directory). However the pdf files within the given directory have revision letters at the end of their file names, starting with 'A' for the first revision and 'B' for the second revision...and so on.
So I am trying to approach it like comparing the string to the files in the directory and then once it's found, check what the latest rev letter is if any.
So if there is 07010302A.pdf file in the directory and there's also a 07010302B.pdf in the directory, I want to store that file name (07010302B.pdf) to a new string in my vb application. Any help on this would be much appreciated.
Here's what I am working with:
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim range As Excel.Range
Dim rCnt As Integer
Dim cCnt As Integer
Dim Obj As Object
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Open("C:\Users\Admin\Desktop\Exp_Master.xlsm")
xlWorkSheet = xlWorkBook.Worksheets("Sheet1")
range = xlWorkSheet.Range("H1:H100") 'xlWorkSheet.UsedRange
For rCnt = 1 To range.Rows.Count
For cCnt = 1 To range.Columns.Count
Obj = CType(range.Cells(rCnt, cCnt), Excel.Range)
If IsNumeric(CType(range.Cells(rCnt, cCnt), Excel.Range).Value) Then
'MsgBox(Obj.value)
ListView1.Items.Add(Obj.value)
ListView1.View = View.List
End If
Next
Next
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
'Kill Excel Process that wouldn't close
Process.Start("C:\Users\Admin\Desktop\batch archive\EXCEL_KILLER.bat")
'MsgBox("Total Item(s) in ListView:" & ListView1.Items.Count)
Dim i As Integer = 0
Dim n As Integer = 0
Dim str As String
For i = 1 To (ListView1.Items.Count)
Dim strng As String = "R:\"
n = (i - 1)
str = strng & (ListView1.Items.Item(n).Text) & (".pdf")
MsgBox(str)
'----
'System.Diagnostics.Process.Start(str)
'Here I want to check the R:\ directory and compare it with each string to see
'what the latest revision letter of the filename is and store it in another string to add to
'a pdf merging list later in this for loop
'----
Next
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
End Class
I was able to use your Directory.getfiles suggestion and I added a for loop to display only the last of the files labeled within that criteria. Thanks a bunch, just took a little more playing with it to determine what I actually wanted and how to put it in code.
If anyone cares, here is the update that works and gets the last file name and path of the directory.getfiles group within a search criteria.
Cheers!
For i = 1 To (ListView1.Items.Count)
Dim strng As String = "R:\"
n = (i - 1)
str = strng & (ListView1.Items.Item(n).Text) & (".pdf")
'MsgBox(str)
Dim substr As String
substr = str.Substring(3, 8)
'MsgBox(substr)
'----
'System.Diagnostics.Process.Start(str)
' Only get files that begin with...
Dim dirs As String() = Directory.GetFiles("R:\", (substr & ("*.pdf")))
'MsgBox("The number of files starting with your string is {0}.", dirs.Length)
Dim dir As String
For Each dir In dirs
If dir Is dirs.Last Then
MsgBox(dir)
'do something with your last item'
End If
Next
'----
Next
End Sub

Renaming files listed within a listbox

I'm trying to create a little program thats able to alter the names of shotcuts, from a listbox-index.
I've created a button wich list every file with the targeted "extension"(targeted with combobox1), from where I want another button to be able to alter the files names:
Button 1 code(Searching for the files):
Dim kilde As New FolderBrowserDialog
If kilde.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim mappe = New System.IO.DirectoryInfo(kilde.SelectedPath)
txtbSti.Text = kilde.SelectedPath
End If
For Each f In Directory.GetFiles(txtbSti.Text, "*" & ComboBox1.Text & "*", SearchOption.AllDirectories)
If File.Exists(f) Then
With ListBox1
With .Items
.Add(f)
End With
End With
End If
Next f
This gives me a list with the desired files.
Is there a way, to rename the files, in my case,listed within listbox1, line by line?
Button 2 (not functioning)
For Each r As String In ListBox1.Items
System.IO.Path.ChangeExtension(ComboBox1.Text, " ")
Next r
You can use File.Move to "rename" a file:
System.IO.File.Move("oldfilename", "newfilename")
For example:
For Each oldFilePath As String In ListBox1.Items
If System.IO.File.Exists(oldFilePath) Then
Dim dir = System.IO.Path.GetDirectoryName(oldFilePath)
Dim newFilePath = System.IO.Path.Combine( dir, "newFileName")
System.IO.File.Move(oldFilePath, newFilePath)
End If
Next
Edit: In this case, remove the automatic generated extension ".avi - Shortcut"
If you just want to change an extension you can use Path.ChangeExtension:
System.IO.Path.ChangeExtension(oldFilePath, "new_extension")
Update: oh, sorry, it's a part of the name; the file is named, example; J:\Homemovies\Jumping around.avi - Shortcut.lnk, I want to remove the ".avi - Shortcut" part of the name on the actual file(s) listed within the listbox1 that is set up to find all the files within a targeted folder with that particular extension within it's name; J:\Homemovies\Jumping around.lnk
You can use String.Replace:
Dim name = System.IO.Path.GetFileName(oldFilePath).ToLowerInvariant()
Dim newName = name.Replace(".avi - shortcut.", ".")
Dim newPath = System.IO.Path.Combine(
System.IO.Path.GetDirectoryName(oldFilePath), newName)
Update2: still can't get either of those solutions to work
Here is a complete working sample:
First, read the shortcuts from your directory:
Dim dir = "C:\Temp\Homemovies"
For Each fn In Directory.EnumerateFileSystemEntries(dir, "*avi - shortcut*.*", SearchOption.AllDirectories)
ListBox1.Items.Add(fn)
Next
Second (in your button-click handler), rename those .Ink files by removing the part that contains(substring)"avi - shortcut", also handling the case that it already exists:
For Each fn As String In ListBox1.Items
If File.Exists(fn) Then
Dim folder = Path.GetDirectoryName(fn)
Dim fileName = Path.GetFileNameWithoutExtension(fn)
Dim extension = Path.GetExtension(fn)
Dim dotParts = fileName.Split("."c)
Dim allButAviShortCut = From part In dotParts
Where part.IndexOf("avi - shortcut", StringComparison.InvariantCultureIgnoreCase) = -1
Dim newFileName = String.Join(".", allButAviShortCut)
Dim newPath = System.IO.Path.Combine(dir, newFileName & extension)
Dim number = 0
While File.Exists(newPath)
' exists already, append number
number += 1
Dim newFileNameWithNum = String.Format("{0}_{1}", newFileName, number)
newPath = System.IO.Path.Combine(dir, newFileNameWithNum & extension)
End While
System.IO.File.Move(fn, newPath)
End If
Next
Consider the following:
ListBox1 contains list of all files in the selected directory.
txtbSti is the text box which holds the path to the selected directory.
Each file is renamed as New_fileX where X is the index of the file in the ListBox1
Now take a look into the code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Integer = 0
For Each r As String In ListBox1.Items
i += 1
My.Computer.FileSystem.RenameFile(txtbSti.Text & ":\" & r, "New_file" & i & ".txt")
Next r
End Sub