Copy files with multiple search criteria - vb.net

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

Related

Renaming ending of all files in a folder and subfolder (*.log to *.txt)

Is it possible to rename all the files in a folder and subfolder with a simple program, using vb.NET
I'm quite green and not sure if this is even possible.
D:\Main\ <--- there are 10 Files.
D:\Main\Sub\ <--- there are some more files
...
The files has always the ending "log" like "this is a test.log" or "this_is_the_second.log". All the files-ending rename to "txt" like "this is a test.txt" or "this_is_the_second.txt".
I tried allready this code, but it doesn´t work :
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
renameFilesInFolder()
End Sub
Private Sub renameFilesInFolder()
Dim sourcePath As String = "D:\Main"
Dim searchPattern As String = "*.log"
For Each fileName As String In Directory.GetFiles(sourcePath, searchPattern, SearchOption.AllDirectories)
File.Move(Path.Combine(sourcePath, fileName), Path.Combine(sourcePath, ".txt"))
Next
End Sub
Please help me!?!?!
Private Sub RenameFilesInFolder()
Dim sourcePath As String = "D:\Main"
Dim searchPattern As String = "*.log"
For Each currentFilePath As String In Directory.GetFiles(sourcePath, searchPattern, SearchOption.AllDirectories)
Dim newFilePath = Path.ChangeExtension(currentFilePath, ".txt")
File.Move(currentFilePath, newFilePath)
Next
End Sub
The GetFiles method gets the full file path, not just the name. Path.Combine(sourcePath, fileName) would result in values like "D:\MainD:\Main\Sub\test.log" while Path.Combine(sourcePath, ".txt") would have resulted in the value "D:\Main.txt" every time.

Utilizing wildcards and variables for getFiles

I am kinda new to VB.net, so I am not sure if I try this the right way. I have the following piece of code.
Dim objReader As New System.IO.StreamReader(FILE_NAME)
Dim TextLine As String
Do While objReader.Peek() <> -1
Dim newString As String = TextLine.Replace(vbCr, "").Replace(vbLf, "") & ".wav"
Dim SongName As String = My.Computer.FileSystem.GetName(newString)
Dim MyFile As String = Dir("C:\AllSongs\" & newString)
Dim Searchquery As IEnumerable(Of String) = IO.Directory.EnumerateFiles("C:\AllSongs", "*", IO.SearchOption.AllDirectories).Where(Function(f) IO.Path.GetFileNameWithoutExtension(f).IndexOf(SongName, StringComparison.CurrentCultureIgnoreCase) >= 0)
For Each Result In Searchquery
ListBox1.Items.Add(Result)
Next
I am trying to use the lines in the text file, and get the .wav in AllSongs dir that partially correspond in these files. Can it be done?
Edit: Part of the code contains a media player. I want to be able to play songs from this player, by choosing files in the list.
Private Sub ListBox1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.DoubleClick
AxWindowsMediaPlayer1.URL = ListBox1.SelectedItem
Dim variables As New Dictionary(Of String, String)()
Dim selectedItem As Object = ListBox1.SelectedItem
variables("MyDynamicVariable") = selectedItem ' Set the value of the "variable"
selectedItem1 = selectedItem
Dim value As String = variables("MyDynamicVariable") ' Retrieve the value of the variable
End Sub
Incidental to the question, but important, is that when you're working with files it's often necessary to clean up some resources (file handles, I guess) that the operating system uses even though you don't see it directly in the code as written. There is a way of doing that automatically with the Using statement, as shown in the following code.
To find out if a filename contains some text (string), you can extract the filename with no path or extension with Path.GetFileNameWithoutExtension and check if it contains the desired string with the IndexOf function, which lets you ignore uppercase/lowercase by specifying how to do the check.
I notice from an update to the question that some improvements can be made, such as using a Class for the song entries so that the displayed list can have more information behind it, which means that the song name can be shown on its own but you can get the full path to the file when you click on it.
I made a new Windows Forms project and added just a ListBox to it, and used this code to show the full path (which you can use for your media player) to the song when its name is double-clicked:
Imports System.IO
Public Class Form1
Public Class SongEntry
Property Name As String
Property FullName As String
End Class
Sub PopulateSongList(musicDirectory As String, songsList As String)
Dim songList As New List(Of SongEntry)
Using sr As New System.IO.StreamReader(songsList)
Do While Not sr.EndOfStream
Dim thisSong = sr.ReadLine()
If thisSong <> "NaN" Then
Dim fs = Directory.EnumerateFiles(musicDirectory, "*.wav", SearchOption.AllDirectories).
Where(Function(f) Path.GetFileNameWithoutExtension(f).IndexOf(thisSong, StringComparison.CurrentCultureIgnoreCase) >= 0).
Select(Function(g) New SongEntry With {.Name = Path.GetFileNameWithoutExtension(g), .FullName = g})
songList.AddRange(fs)
End If
Loop
End Using
ListBox1.DataSource = songList
ListBox1.DisplayMember = "Name"
ListBox1.ValueMember = "FullName"
End Sub
Private Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles ListBox1.DoubleClick
Dim lb = DirectCast(sender, ListBox)
If lb.SelectedIndex >= 0 Then
Dim fullPathToSong = lb.SelectedValue.ToString()
MsgBox(fullPathToSong)
End If
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim songsList = "C:\temp\AllSongs\songsList.txt"
Dim musicDirectory = "C:\temp\AllSongs"
PopulateSongList(musicDirectory, songsList)
End Sub
End Class

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.

Problems with splitt out SIP-Address from AppData\Local\Microsoft\Office\16.0\Lync

I'm trying to split out the sip_address in folder C:\Users\%username%\AppData\Local\Microsoft\Office\16.0\Lync Since I have more than one active SIP-addresses I have some problems getting the one I need in this example it would be example2#example2.com
There might also be more SIP-addresses in this folder, but I would only like to have the one example2.
I started with sorting out all subfolder in directory giving me a result:
C:\Users\%username%\AppData\Local\Microsoft\Office\16.0\Lync\sip_example1#example1.com
C:\Users\%username%\AppData\Local\Microsoft\Office\16.0\Lync\sip_example2#example2.com
C:\Users\c%username%\AppData\Local\Microsoft\Office\16.0\Lync\Tracing
And here is where face issues with splitting as my code are not good at all and the result would be:
example2#example2.comC:\Users\%username%\AppData\Local\Microsoft\Office\16.0\Lync\Tracing
Imports System.IO
Public Class Form1
Dim SIPAccount As String
Private Sub GETSipAccount()
' Path and SIP-Addresses has been anonymous due to personal addresses.
For Each Dir As String In Directory.GetDirectories("C:\Users\%username%\AppData\Local\Microsoft\Office\16.0\Lync")
' List out directory
SIPAccount = SIPAccount & Dir & vbNewLine
On Error Resume Next ' I do not want to include this in my application at all
' Splits out text
SIPAccount = ((Split(Split(SIPAccount, "sip_")(1), "#example2.com")(0))) & "#example2.com"
MsgBox(SIPAccount)
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
GETSipAccount()
End Sub
depending if the "example2" string part is unique to the directory address you could use something like
Dim lst As List(Of String) = IO.Directory.GetDirectories("C:...").ToList
MessageBox.Show(lst.FindAll(Function(x) x.Contains("example2"))(0))
if you want to compare just the last part of the string you could use something like
Dim lst As List(Of String) = IO.Directory.GetDirectories("C:...").ToList
For Each item As String In lst
Dim lastindexofbackslash As Integer = item.LastIndexOf("\")
Dim _item As String = item.Substring(lastindexofbackslash + 1)
If _item.Contains("example2") Then
MsgBox(_item.Substring(4))
End If
Next

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