Utilizing wildcards and variables for getFiles - vb.net

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

Related

"The given path's format is not supported" on form load,

I am making an application for school. It has four buttons and one of which opens a logs window. It gets all of the text files in each folder and displays them in a DataGridView. All of this is on a mapped network drive on a domain controller. When the form with the table loads it throws "The given path's format is not supported." This is my code:
Imports System.IO
Public Class Form2
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt As New DataTable
dt.Columns.Add("Date/Time")
dt.Columns.Add("Username")
dt.Columns.Add("Room")
For Each dir As String In Directory.GetDirectories("T:\(IncidentReport)\logs")
Dim infoa As New IO.DirectoryInfo("T:\(IncidentReport)\logs\" + dir)
Dim infob As IO.FileInfo() = infoa.GetFiles("*.txt")
Dim infoc As IO.FileInfo
For Each infoc In infob
Dim log() As String
log = File.ReadAllLines("T:\(IncidentReport)\logs\" + dir + "\" + infoc.Name)
Dim row = dt.NewRow()
row(0) = log(0)
row(1) = log(2)
row(2) = log(1)
dt.Rows.Add(row)
Next
Next
DataGridView1.DataSource = dt
End Sub
End Class
Any ideas anyone? Bit stuck here...
(I've tried changing them to my "user area" on my domain user which I have 100% control on and there was no difference)
The Directory.GetDirectories() function returns FULL PATH strings:
Returns String[] An array of the full names (including paths) of
subdirectories in the specified path, or an empty array if no
directories are found.
So in your next line of code:
Dim infoa As New IO.DirectoryInfo("T:\(IncidentReport)\logs\" + dir)
You're concatenating a full path with another full path, which obviously won't work.
I'd approach it more like below, to side step these kinds of issues. This re-work creates a DirectoryInfo from your main folder, then retrieves the subfolders with DirectoryInfo.GetDirectories(). From there, we iterate over FileInfo instances via DirectoryInfo.GetFiles(). Lastly, we get the full path filename with FileInfo.FullName:
Dim dt As New DataTable
dt.Columns.Add("Date/Time")
dt.Columns.Add("Username")
dt.Columns.Add("Room")
Try
Dim folder As New DirectoryInfo("T:\(IncidentReport)\logs")
For Each subFolder As DirectoryInfo In folder.GetDirectories
For Each FI As FileInfo In subFolder.GetFiles("*.txt")
Dim lines() As String = File.ReadAllLines(FI.FullName)
If lines.Length >= 3 Then
dt.Rows.Add(New Object() {lines(0), lines(1), lines(2)})
End If
Next
Next
Catch ex As Exception
MessageBox.Show(ex.ToString, "Error Reading Files")
End Try
DataGridView1.DataSource = dt
We can flatten this code considerably. Also, never pass up the chance to move code out of an the immediate event handler, or to save memory by enumerating items rather than loading them all in an array:
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DataGridView1.DataSource = LoadLogFiles("T:\(IncidentReport)\logs")
End Sub
Public Function LoadLogFiles(ByVal basePath As String) As DataTable
Dim result As new DataTable()
result.Columns.Add("Date/Time")
result.Columns.Add("Username")
result.Columns.Add("Room")
Dim dir As New DirectoryInfo(basePath)
For Each fileInfo In dir.EnumerateFiles("*.txt", SearchOption.AllDirectories)
Dim row = result.NewRow()
Dim column As Integer = 0
'This is better if a log could have many lines and you only care about the first three.
'If the files only have exactly three lines, just read to an array like you were.
For Each line As String In File.ReadLines(fileInfo.Name).Take(3)
row(column) = line
column += 1
Next
result.Rows.Add(row)
Next
Return result
End Sub

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

Parsing String into an Array (VB)

I have tried to make a program that would parse a raw list from Chrome://policy (input by RichTextbox) into a text array, then dump it into another RichTextbox. All of the raw string are exactly 32 characters long, followed by a comma. Here is the code:
Public Class Form1
Dim tempExt As String
Dim extsHandled As Integer
Dim numOfExts As Integer
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If RichTextBox1.Text = "" Then
MsgBox("Please enter the raw extensions from Chrome://policy")
Else
RichTextBox3.Text = RichTextBox1.Text
numOfExts = TextBox1.Text
Dim place As Integer = 0
Dim exts(150) As String
While extsHandled < numOfExts
tempExt = RichTextBox1.Text.Substring(0, 32)
exts(place) = tempExt
RichTextBox1.Text.Remove(0, 33)
place = place + 1
extsHandled = extsHandled + 1
End While
Dim newPlace As Integer = 0
While newPlace < numOfExts
RichTextBox2.AppendText(exts(newPlace))
newPlace = newPlace + 1
RichTextBox2.AppendText(" ")
End While
End If
End Sub
End Class
Most of it works, but it would seem something is going wrong with removing the characters from the richtextbox, as when I run it, it only parses the first part of the string over and over:
Am I doing something wrong?
If it's always like that you can do it like this:
RichTextBox3.Text = RichTextBox1.Text.Replace(",", vbNewLine)
The #3 is your result, while #1 is original right?
Ah yeah, you can count how many there simply by
RichTextBox2.Text= RichTextBox1.Text.Split({","}, StringSplitOptions.RemoveEmptyEntries).Count.ToString
This line returns a new string:
RichTextBox1.Text.Remove(0, 33)
It does not modify the textbox in place. The next iteration through the loop, you're still working with the original value, looking at the same set of 32 characters at the beginning of the string.
Additionally, nothing in this code initializes the extsHandled variable. You should turn on Option Strict, which helps catch that kind of error. Running of Option Strict off is poor practice. You should also give a meaningful name to any control you will actually reference from code.
It's not clear to me right now the exact format. If it's all on the same line (no line break characters as part of the string, even if it wraps), this should work:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If String.IsNullOrWhitespace(RichTextBox1.Text) Then
MsgBox("Please enter the raw extensions from Chrome://policy")
Exit Sub
End If
RichTextBox3.Text = RichTextBox1.Text
Dim exts() As String
Using rdr As New TextFieldParser(RichTextBox1.Text)
rdr.TextFieldType = FileIO.FieldType.Delimited
rdr.Delimiters = New String() {","}
exts = rdr.ReadFields()
End Using
For Each ext As String In exts
RichTextBox2.AppendText(ext)
Next ext
RichTextBox1.Text = ""
End Sub
The problem is this code doesn't do anything. The array is gone when the method ends. Consider making the array a property of the class, or having method that returns the array as the result.
You can also look at this, to save typing into the textbox, though it's just a starting point:
Public Function GetChromeExtensionKeys() As IEnumerable(Of String)
Dim BasePath As String =
EndEnvironment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
BasePath = Path.Combine(BasePath, "Google\Chrome\User Data")
Dim dflt As String = Path.Combine(BasePath, "Default\Extensions")
Dim profileExts() As String = Directory.GetDirectories(BasePath, "Profile *").
Select(Function(p) Path.Combine(p, "Extensions"))
Dim result As New List(Of String)()
result.AddRange(Directory.GetDirectories(dflt))
For Each folder As String In profiles
result.AddRange(Directory.GetDirectories(folder))
Next folder
Return result.Select(Function(e) Path.GetFileName(e)).Distinct()
Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For Each ext As String In GetChromeExtensionKeys()
RichTextBox2.AppendText(ext)
Next ext
End Sub

how to read from text file to textbox in visual basic 1 line every hit on button

I have files type .txt (Text File) and it's have multiple line and i have these pictures
i want to make program generate fake information
Mean: when some one hit generate button it's ready from text file and fill textbox in visual basic
every hit(press) on Generate Button make program generate new information from text files (.txt)
i tried a lot ways:
Code:
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText("C:\test.txt")
Code:
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText("C:\test.txt", _
System.Text.Encoding.UTF32)
and this
Code:
Dim oFile as System****.File
Dim oRead as System****.StreamReader
oRead = oFile.OpenText(“C:\test.txt”)
and this
Code:
Dim FILE_NAME As String = "C:\Users\user\Desktop\test.txt"
Dim objReader As New System.I--O.StreamReader(FILE_NAME)
TextBox1.Text = objReader.ReadToEnd
Code:
' Form Load :
Dim text As String = MsgBox("text you want to make the form remember it.")
Or new Sub :
Code:
Private Sub Text
text
Code:
' Button Click :
Text()
Code:
Dim path As String = "THE FILE PATH" 'The file path
Dim reader As New IO.StreamReader(path)
Dim lineIndex As Integer = 2 ' The index of the line that you want to read
For i As Integer = 0 To lineIndex - 1
reader.ReadLine()
Next
TextBox1.Text = reader.ReadLine
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
TextBox1.Text = ReadLineFromTxt("THE TXT FILE PATH", 0) '0 is the line index
End Sub
Public Shared Function ReadLineFromTxt(ByVal path As String, ByVal lineIndex As Integer) As String
Dim reader As New IO.StreamReader(path)
For I As Integer = 0 To lineIndex - 1
reader.ReadLine()
Next
Return reader.ReadLine()
End Function
End Class
These ways take from members in this fourm:
http://www.mpgh.net/forum/33-visual-basic-programming/693165-help-how-can-i-generate-text-txt-file-textbox-when-button-click-2.html
if are these ways working please tell me how to use it in best way
i have Visual studio 2012 and updated 1
With all due respect
Assuming you are reading from a file and displaying lines on the form, you can use these.
If you have a large file (> 10MB), then you can use this pattern... (syntax from memory, please excuse mistype)
Public Class YourFormNameHere
Private _CurrentLine as Integer = 0
Private Sub btnClicked(sender, e) 'or enter pressed - This is YOUR keypress event handler.
Using Dim sr as New StreamReader(filePath)
Dim _curIndex as Integer = 0
While (sr.EndOfFile == false)
Dim _line as String = sr.ReadLine()
If (_curIndex = _CurrentLine)
txtLineDisplay.Text = _line
Break
End If
curIndex += 1
End While
End Using
End Sub
End Class
If you have a smaller file, then use this pattern.
Public Class YourFormNameHere
Private _Lines as String()
Private _CurrentLine as Integer = 0
Private Sub formLoad(sender, e) 'one-time load event - This is YOUR form load event
_Lines = File.ReadAllLines(filePath)
End Sub
Private Sub btnClicked(sender, e) 'or enter pressed - This is YOUR keypress event handler.
txtLineDisplay.Text = _Lines(_CurrentLine)
_CurrentLine += 1
End Sub
End Class

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.