Add Multiple extensions to string VB.net - vb.net

I have the below code that looks for the value displayed in a combobox then populates a listbox with the selected file names that relate the extension selected (maybe the code will make more sense!)
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim lyxfle As New IO.DirectoryInfo(sPath)
Dim diar1 As IO.FileInfo() = lyxfle.GetFiles()
Dim MyExt As String = Nothing
Dim MyVariable As String
Dim sFile As String
MyVariable = ComboBox1.Text
If MyVariable = "Forms" Then MyExt = "*.pff"
If MyVariable = "Reports" Then MyExt = "*.mdb"
If MyVariable = "Spreadsheets" Then MyExt = "*.xlsm"
ListBox2.Items.Clear()
sFile = Dir$(sPath & MyExt)
Do While CBool(Len(sFile))
ListBox2.Items.Add(System.IO.Path.GetFileNameWithoutExtension(sFile))
sFile = Dir$()
Loop
End Sub
The following line is what i'm struggling with
If MyVariable = "Spreadsheets" Then MyExt = "*.xlsm"
I basically need it to also look at the extensions .xls & .xlsx and include all files within the list
Both Path and sPath are declared as Private Strings at the top of the class
Any advice

I'll try to keep this simple and use what you have then. This code will get all the files from the folder. Then it will match it to your MyExt selection. As you can see I have added the excel file extensions with a comma between them (can be any special character really). Then all I have to do is see if MyExt contains the FileExtension and add it to the listbox:
Dim MyExt As String = Nothing
Dim MyVariable As String
Dim sFile As String
MyVariable = ComboBox1.Text
If MyVariable = "Forms" Then MyExt = "*.pff"
If MyVariable = "Reports" Then MyExt = "*.mdb"
If MyVariable = "Spreadsheets" Then MyExt = ".xlsm,.xls"
Dim lyxfle As New IO.DirectoryInfo(sPath)
Dim diar1 As IO.FileInfo() = lyxfle.GetFiles()
For Each file As IO.FileInfo In diar1
If MyExt.Contains(file.Extension) Then
ListBox2.Items.Add(IO.Path.GetFileNameWithoutExtension(file.Name))
End If
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.

vb.net Creating folders for each files in the listbox

listbox1 lists sub-folders that contain files.
listbox2 has files list.
When button1 is pressed I hope the folders are made for each files in the listbox2(folder name should be as same as file name) and then move corresponding file to that directory.
eg)
listbox1
d:\data\sub1\
listbox2
d:\data\sub1\a.7z
d:\data\sub1\ab.7z
when button1 is pushed
we can find the files in...
d:\data\sub1\a\a.7z
d:\data\sub1\ab\a.7z
I'm having trouble to make it. I know how to list files in the listbox but I don't know how to deal with each of them.
Also, if I try to get rid of 7z extension in the directory name with the following code, it says it can not be used for the listbox.
If folderslist.SelectedItem IsNot Nothing Then
' selected item is filepath
Dim filePath = folderslist.SelectedItem.ToString
The string you are searching
Dim s As String = filePath
Find index of uppercase letter 'B'
Dim i As String = 0
Dim j As String = s.IndexOf("."c)
This new string contains the substring starting at B
part = s.Substring(i, j - i + 1)
If (s.IndexOf(".") = -1) Then
part = "Not found"
End If
Any advice, please.
You don't need to manually split the path to get separate strings. Use
System.IO.Path.GetFileName, and
System.IO.Path.GetFileNameWithoutExtension and
System.IO.Path.GetDirectoryName.
And the like.
It's a little difficult to give a direct, explicit example, because it's quite unclear what you want to do based on what you're shown. But as an example...
Dim basePath as String = "d:\data\sub1\"
Dim fullName as String = folderslist.SelectedItem.ToString()
Dim fileName as String = Path.GetFileName(fullName)
Dim partialName as String = Path.GetFileNameWithoutExtension(fullName)
Dim newPath as String = Path.Combine(basePath, partialName)
newPath = newPath + Path.Combine(newPath, fileName)
Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
If folderslist.SelectedItem IsNot Nothing Then
Dim filePath = folderslist.SelectedItem.ToString
fileslist.Items.Clear()
Dim dirf As String() = Directory.GetFiles(filePath, "*.7z")
Dim dira As String
For Each dira In dirf
fileslist.Items.Add(dira)
Next
If mkfold = 1 Then
For Each dira In dirf
Dim pName As String = Path.GetFileNameWithoutExtension(dira)
Dim strDir As String
strDir = filePath & "\" & pName
If DirExists(Trim(strDir)) = False Then
MkDir(Trim(strDir))
End If
Dim f_name As String = Path.GetFileName(dira)
My.Computer.FileSystem.MoveFile(dira, strDir & "\" & f_name)
Next
mkfold = 0
End If
End If
Private Sub mkfol_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mkfol.Click
mkfold = 1
End Sub
Somehow I got what I wanted.

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