I have a text file delimited by pipes. I want to read the value at the fifth pipe but I cannot figure out how to do that. All I can do is read each section of the array. Can't find examples on this.
EPD|TR2999-01G|SEMI, TRANS, P-CH, SEL|ACTIVE|PS.COE.6|SCS|SCREENEDCOMPONENTS|EPP|Buy|6.237|916.839|147||181|||CCACOE||PS.777.||150||
EPD|TR2309-01G|SEMI, TRANS, P-CH, SEL|ACTIVE|PS.COE.6|SCS|SCREENED COMPONENTS|EPP|Buy|6.237|193.347|31||181|||777||PS.777.||150||
This example is using a text file with these two lines in it:
Line1: EPD|TR2999-01G|SEMI, TRANS, P-CH, SEL|ACTIVE|PS.COE.6|SCS|SCREENED COMPONENTS|EPP|Buy|6.237|916.839|147||181|||CCACOE||PS.777.||150||
Line2: EPD|TR2309-01G|SEMI, TRANS, P-CH, SEL|ACTIVE|PS.COE.6|SCS|SCREENED COMPONENTS|EPP|Buy|6.237|193.347|31||181|||777||PS.777.||150||
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim fp as string = "" 'enter the full path to your file here
Dim value as string = GetValueForPart(fp, Me.TextBox1.Text)
MsgBox(value) 'in this example, value is set to "6.237" when textbox input is "TR2999-01G"
End Sub
Private Function GetValueForPart(ByVal filepath As String, ByVal SearchPartNum As String) As String
If Not File.Exists(filepath) Then Return Nothing
If SearchPartNum Is Nothing OrElse SearchPartNum.Trim = "" Then Return Nothing
Dim ret As String = Nothing
Using sr As New StreamReader(filepath)
Do While sr.Peek >= 0
Dim line() As String = sr.ReadLine.Split(CChar("|"))
If line IsNot Nothing AndAlso line.Count >= 5 Then
If line(1).Equals(SearchPartNum) Then
ret = line(9)
Exit Do
End If
End If
Loop
End Using
Return ret
End Function
I just tested this, all you need to do is enter your full filepath on the second line
Related
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
Dim EmpId(100) As String
Dim Lastname(100) As String
Dim firstname(100) As String
Dim hrs(100) As Integer
Dim min(100) As Integer
Dim counter As Integer
Dim i As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'declare variables
Dim result As DialogResult 'what did the user choose in the open dialog (open or cancel)
Dim strFileName As String 'store file path of the selected file
Dim strRecord As String
Dim sreStreamReader As IO.StreamReader
Dim strFieldValues(100) As String 'to store extracted field values.
Try
result = filebrowser.ShowDialog
If result = Windows.Forms.DialogResult.OK Then
strFileName = filebrowser.FileName
'create a StreamReader object by opening the file for input
sreStreamReader = IO.File.OpenText(strFileName)
counter = 0
i = 0
Do While sreStreamReader.Peek() <> -1
strRecord = sreStreamReader.ReadLine()
strFieldValues = strRecord.Split(",")
EmpId(counter) = strFieldValues(i) & firstname(counter) = strFieldValues(i) & Lastname(counter) = strFieldValues(i) _
& hrs(counter) = strFieldValues(i) & min(counter) = strFieldValues(i)
counter = counter + 1
i = i + 1
Loop
Dim j As Integer
For j = 0 To j < counter Step +1
Label1.Text = EmpId(j) & firstname(j) & Lastname(j) & hrs(j) & min(j)
Next
sreStreamReader.Close()
End If
Catch exFile As IO.FileNotFoundException
'processed when the file cannot be found
MessageBox.Show("Cannot locate the file.", _
"FileopenDialog", MessageBoxButtons.OK, _
MessageBoxIcon.Information)
' Catch ex As Exception
'handles any other errors
' MessageBox.Show(ex.Message, "FileopenDialog", _
' MessageBoxButtons.OK, MessageBoxIcon.Information)
End Try
I am assuming that your text file would look like this if opened in notepad.
1,Smith,Mary,7,45
2,Jones,Bill, 8,15
3,Mathew,Mark,6, 20
4,Luke,John,9,30
Notice there are no spaces. If there are spaces you may have to use .Trim on the strings.
I have a class called Employee. In the class there is a custom constructor (the Sub New) which sets all the appropriate properties. The values will come from the text file as you will see in a minute.
Then in the buttton click event a list of the type Employee is created.
Dim EmpList As New List(Of Employee)
It can hold objects of the type Employee. I use a `List(0f T) instead of an array because I don't have to know ahead of time how many lines are in the file.
The .ReadAllLines method of the File object returns an array containing each line in the file as an element of the array. Loop through the lines array calling .Split on each line which returns an array presumably containing each of the fields you are interested in. Each element is sent to the constructor of Employee and the resulting new Employee is added to the list. If there are extraneous spaces in the file this is where you may need to call .Trim to get rid of them
Finally, I have added a DataGridView to the form at design time. Set the .DataSource property to the list of employees and your data is displayed in the grid with headers.
Public Class Employee
Public Property ID As String
Public Property LasName As String
Public Property FirstName As String
Public Property Hours As Integer
Public Property Minutes As Integer
Public Sub New(iden As String, lname As String, fname As String, hr As Integer, mn As Integer)
ID = iden
LasName = lname
FirstName = fname
Hours = hr
Minutes = mn
End Sub
End Class
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim EmpList As New List(Of Employee)
Try
Dim result = OpenFileDialog1.ShowDialog
If Not result = Windows.Forms.DialogResult.OK Then
MessageBox.Show("No file selected")
End If
Dim strFileName = OpenFileDialog1.FileName
Dim lines = IO.File.ReadAllLines(strFileName)
For Each line In lines
Dim strFieldValues = line.Split(","c)
EmpList.Add(New Employee(strFieldValues(0), strFieldValues(1), strFieldValues(2), CInt(strFieldValues(3)), CInt(strFieldValues(4))))
Next
DataGridView1.DataSource = EmpList
Catch exFile As IO.FileNotFoundException
MessageBox.Show("Cannot locate the file.", "FileopenDialog", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Try
End Sub
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
I have a working program, but it's like Frankenstein - parts of other programs put together, that may be redundant. Here's what I'm trying to do:
Find a string inside a binary file & from that location to the EOF dump the contents into a string.
Here is my code:
Imports System.IO
Public Class Form1
Dim b() As Byte = IO.File.ReadAllBytes("C:\data.bin")
Dim encodme As New System.Text.ASCIIEncoding
Dim SearchString As String = "xyzzy"
Dim bSearch As Byte() = encodme.GetBytes(SearchString)
Dim bFound As Boolean = True
Dim oneByte As Byte
Dim fileData As New IO.FileStream("C:\data.bin", FileMode.Open, FileAccess.Read)
Dim strMessage As String
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
For i As Integer = 0 To b.Length - bSearch.Length - 1
If b(i) = bSearch(0) Then
bFound = True
For j As Integer = 0 To bSearch.Length - 1
If b(i + j) <> bSearch(j) Then
bFound = False
Exit For
End If
Next
If bFound Then
fileData.Seek(i + 5, SeekOrigin.Begin)
strMessage = ""
For r As Integer = (i + 5) To fileData.Length() - 1
oneByte = fileData.ReadByte()
strMessage = strMessage + Chr(oneByte)
Next r
MsgBox(strMessage)
Else
MsgBox("File Doesn't have string")
Exit Sub
End If
End If
Next
End Sub
End Class
When looking for performance, it is best to avoid trying to walk through this kind of thing byte by byte. Instead you should use the facilities .NET provides you with. This example uses RegEx to find all matches of a string in any file, returning each match with everything that follows it until the next match or the end of the file in a UTF-8 string:
Imports System.IO
Imports System.Text
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim matches = FindStringMatchesInFile("C:\Infinite Air\snowboarding.exe", "data")
For Each m In matches
...
Next
End Sub
Private Function FindStringMatchesInFile(filename As String,
searchString As String) As List(Of String)
Dim output As New List(Of String)
Dim reader = New StreamReader(filename, Encoding.UTF8)
Dim re = New Regex(String.Format("{0}(?:(?!{0}).)*", searchString),
RegexOptions.Singleline Or RegexOptions.IgnoreCase,
Regex.InfiniteMatchTimeout)
Dim matches = re.Matches(reader.ReadToEnd())
For Each m As Match In matches
output.Add(m.ToString())
Next
Return output
End Function
End Class
The RegEx pattern definition is the following:
Matches the characters {searchString} literally (case insensitive)
Non-capturing group (?:(?!{searchString}).)*
* Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
Negative Lookahead (?!{searchString})
Assert that the Regex below does not match
Matches the characters {searchString} literally (case insensitive)
. matches any character
Global pattern flags
g modifier: global. All matches (don't return after first match)
s modifier: single line. Dot matches newline characters
i modifier: case insensitive.
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