I need to read the Config file for load settings.
My code:
Dim preferences As FileInfo
preferences = New FileInfo(".\settings.conf")
If preferences.Exists Then
Dim objReader As New System.IO.StreamReader(".\settings.conf")
Dim tmpLine_theme As String
Do While objReader.Peek() <> -1
tmpLine_theme = objReader.ReadLine()
If tmpLine_theme.StartsWith("theme_selected: ") Then
tmpLine_theme = tmpLine_theme.Replace("theme_selected: ", "")
theme_box.Text = tmpLine_theme
MsgBox("Theme:" + tmpLine_theme)
theme_selected_var = tmpLine_theme
Else
MsgBox("Not working")
End If
Loop
This code causes a loop, through which can't go on.
I need to get the specific word, which then removes and retrieves the required data.
If i get you correctly,you are trying to get the line which contains specific word ? It isn't that hard , just a few lines of code :)
Dim readFile as New List(of String)(File.ReadAllLine("path of file"))
For each line in readFile
If line.Contains("theme_selected: ") Then
line.Replace("theme_selected: ","")
MsgBox(line)
End if
Next
Related
I'm trying to save a class to a text file and I'm getting mixed results. Half the time the last line of the add is in the file and sometimes not. I've not been able to get a consistent output to the file.
So, I added a debug to show me what was being written just prior to the StreamWriter.Write and it showed the line that I added but it doesn't show up in the file.
^ This line is the last line that isn't being written to the file.
Here's what my code where I save the data looks like:
Private sub SaveMemoUsersFile()
If _memoList is Nothing Then
return
End If
Dim memofile = Path.Combine(Configuration.DataFileLocations, $"{Configuration.CompanyID}ucMemoUsers.txt")
Const quote As String = """"
Const comma As String = ","
Dim both = $"{quote}{comma}{quote}"
Using sw = New StreamWriter(memofile)
For Each memoUsers As MemoUsers In _memoList
Dim sb = New StringBuilder()
sb.Append(quote)
sb.Append(memoUsers.Initials)
sb.Append(both)
sb.Append(memoUsers.EmailAddress)
sb.Append(both)
sb.Append(memoUsers.DelinquentLetterCode)
sb.Append(both)
sb.Append(memoUsers.Description)
sb.Append(quote)
'sb.Append(vbCr)
console.write(sb) <--- shows the last line
sw.WriteLine(sb.ToString()) <--- but doesn't write it to the file
Next
End Using
_memoList = nothing
End sub
Anyone have any suggestions? I'm completely lost as to why this is writing to the file randomly.
Might as well just build your file in the stringbuilder and write it:
Private sub SaveMemoUsersFile()
If _memoList is Nothing Then
return
End If
Dim q = """"
Dim b = $"{q},{q}"
Dim sb = New StringBuilder()
For Each memoUsers As MemoUsers In _memoList
sb.Append(q)
sb.Append(memoUsers.Initials).Append(b)
sb.Append(memoUsers.EmailAddress).Append(b)
sb.Append(memoUsers.DelinquentLetterCode).Append(b)
sb.Append(memoUsers.Description).AppendLine(q)
Next
Dim memofile = Path.Combine(Configuration.DataFileLocations, $"{Configuration.CompanyID}ucMemoUsers.txt")
IO.File.WriteAllText(memoFIle, sb.ToString())
_memoList = nothing
End sub
in my File Text I have the following things:
I have to make it start from somewhere and stop at a certain point.
but he only starts from that point, but he does not know how to stop at one point.
[Letters]
A
B
C
D
E
[Loop]
[Words]
Fish
Facebook
Google
Youtube
I should display Expected Output:
A
B
C
D
E
Then I should make it display
Fish
Facebook
Google
Youtube
but it shows me:
[Letters]
A
B
C
D
E
[Loop]
[Words]
Fish
Facebook
Google
Youtube
Code
Dim line As String
Using reader As StreamReader = New StreamReader(My.Application.Info.DirectoryPath & "\TestReader.txt")
line = reader.ReadLine
Dim sb As New StringBuilder
Do
Do
If reader.Peek < 0 Then 'Check that you haven't reached the end
Exit Do
End If
line = reader.ReadLine
If line.StartsWith("[Letters]") AndAlso line.EndsWith("[Loop]") Then 'Check if we have reached another check box.
Exit Do
End If
sb.AppendLine(line)
Loop
TextBox1.Text = sb.ToString
sb.Clear()
Loop Until reader.Peek < 0
End Using
This assumes that startPrefix and endPrefix will always be present in the file:
Dim startPrefix As String 'Set as required
Dim endPrefix As String 'Set as required
Dim lines As New List(Of String)
Using reader As New StreamReader("file path here")
Dim line As String
'Skip lines up to the first starting with the specified prefix.
Do
line = reader.ReadLine()
Loop Until line.StartsWith(startPrefix)
line = reader.ReadLine()
Do Until line.StartsWith(endPrefix)
lines.Add(line)
line = reader.ReadLine()
Loop
End Using
'Use lines here.
Are you really sure that you want to look for lines that start with those markers though? Wouldn't you really prefer to look for lines that are equal to those markers?
EDIT:
You could - and probably should - encapsulate that functionality in a method:
Private Function GetLinesBetween(filePath As String, startPrefix As String, endPrefix As String) As String()
Dim lines As New List(Of String)
Using reader As New StreamReader(filePath)
Dim line As String
'Skip lines up to the first starting with the specified prefix.
Do
line = reader.ReadLine()
Loop Until line.StartsWith(startPrefix)
line = reader.ReadLine()
'Take lines up to the first starting with the specified prefix.
Do Until line.StartsWith(endPrefix)
lines.Add(line)
line = reader.ReadLine()
Loop
End Using
Return lines.ToArray()
End Function
i'm trying to importe a csv file after creating on the same application, the only probleme is that even if a string matchs a line from the file, comparing them on vb.net dosn't give a true boolean i know i didn't make any mistakes because of the line with the commentary 'THIS LINE , i use a pretty small list to do my test and in that loop, there is always one element that matches exactly the string, but comparing them on vb.net dosn't return a true. the result of this is that just after saving the file to my computer while still having it on my listview1 on the application, i load it to the application again and it duplicates everything
Dim open As New OpenFileDialog
open.Filter = "CSV Files (*.csv*)|*.csv"
If open.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim File As String = My.Computer.FileSystem.ReadAllText(open.FileName)
Dim lines() As String = File.Split(Environment.NewLine)
For i = 1 To (lines.Count - 1)
Dim line As String = lines(i)
Dim Columns() As String = line.Split(";")
Dim addLin As New ListViewItem(Columns)
Dim Alr As Boolean = False
Dim st as string=listView1.Items.Item(k).SubItems.Item(0).Text
For k = 0 To (ListView1.Items.Count - 1)
Dim st as string=listView1.Items.Item(k).SubItems.Item(0).Text
MsgBox(Columns(0)& Environment.NewLine & st) 'THIS LINE
If ListView1.Items.Item(k).SubItems.Item(0).Text = Columns(0) Then
Alr = True
MsgBox("true") 'never showsup even when the previous one show the match
End If
next
If Alr = False Then
MsgBox("false") 'the msgbox is only to check
ListView1.Items.Add(addLin)
End If
next
end if
I am saving a .csv file in my directory by giving the path with StreamWriter. Now i want to give the option to user to save that file desired path. how can it. help me somebody.
Dim objStreamWriter = New IO.StreamWriter("c:\FaultTypesByMonth.csv")
Dim Str As String
Dim i As Integer
Dim j As Integer
Dim headertext1(rsTerms.Columns.Count) As String
Dim k As Integer = 0
Dim arrcols As String = Nothing
For Each column As DataColumn In TempTab.Columns
headertext1(k) = column.ColumnName
arrcols += column.ColumnName.ToString() + ","c
k += 1
Next
objStreamWriter.WriteLine(arrcols)
For i = 0 To (TempTab.Rows.Count - 1)
For j = 0 To (TempTab.Columns.Count - 1)
'this IF statement stops it from adding a comma after the last field
If j = (TempTab.Columns.Count - 1) Then
Str = (TempTab.Rows(i)(j).ToString)
Else
Str = (TempTab.Rows(i)(j).ToString & ",")
End If
objStreamWriter.Write(Str)
Next
objStreamWriter.WriteLine()
Next
objStreamWriter.Close()
' After save the file in C:/ I want to save the same file in any other Path for my convenience.
'------------------------------------------------------------------------------------------------
Dim sd As New SaveFileDialog
sd.Filter = "CSV Files (*.csv)|*.csv"
sd.FileName = "FaultTypesByMonth"
If sd.ShowDialog = Windows.Forms.DialogResult.OK Then
'save the file here
Debug.WriteLine("Save file location:" + sd.FileName)
End If
If it's a console application you could read a path argument from the command line.
If it's a GUI application you can show a save file dialog box, in WinForms use the SaveFileDialog class.
To save a file to different locations put the writer code in a function which takes the file path as an argument:
Sub SaveFile(filePath As String)
Dim objStreamWriter = New IO.StreamWriter(filePath)
' ... your code here
End Sub
Sub ButtonClick
SaveFile("c:\FaultTypesByMonth.csv")
' ... SaveFileDialog code
SaveFile(sd.Filename)
End Sub
To copy a file use File.Copy:
' ... SaveFileDialog code
File.Copy("c:\FaultTypesByMonth.csv", sd.Filename)
Use the SaveFileDialog class
Simple example:
Private Sub SaveFile()
Dim sd As New SaveFileDialog
sd.Filter = "CSV Files (*.csv)|*.csv"
If sd.ShowDialog = Windows.Forms.DialogResult.OK Then
'save the file here
Debug.WriteLine("Save file location:" + sd.FileName)
End If
End Sub
I need to set this piece of code in vb so that a user can delete a specific string from a .txt document. But when they do, it leaves an empty line. I then got more code to stop this but then it deletes something else within the file with the empty line.
Code:
If (txtDelUser.Text = "admin" Or txtDelUser.Text = "guest") Then
rtbOutput2.Text = "You tried to delete: " + txtDelUser.Text + ". But the user is protected by default."
Else
Dim ln As Integer = 1
rtbOutput.Text.First(Of Text = Text.CopyTo.ClipBoard
'Removes the selected username from list of usernames
Dim lines As New List(Of String)
Using sr As New StreamReader("C:\ProgramData\Hax Client\User Data\All Usernames.txt")
While Not sr.EndOfStream
lines.Add(sr.ReadLine)
End While
End Using
For Each line As String In lines
If line.Contains(txtDelUser.Text) Then
lines.Remove(line)
Exit For 'must exit as we changed the iteration
End If
Next
'End of removing the line
Dim fs As New FileStream("C:\ProgramData\Hax Client\User Data\All Usernames.txt", FileMode.Append)
Dim sw As New StreamWriter(fs)
Dim foundBlank As Boolean
For Each line As String In lines
If line.Length > 0 Then
sw.WriteLine(line)
' Reset blank line flag
foundBlank = False
Else
If Not foundBlank Then
' Blank line: write first one
sw.WriteLine(line)
' Set flag to indicate that blank line was found
foundBlank = True
End If
End If
Next
sw.Close()
fs.Close()
My.Computer.FileSystem.FileExists("C:\ProgramData\Hax Client\User Data\" + txtDelUser.Text)
My.Computer.FileSystem.DeleteFile("C:\ProgramData\Hax Client\User Data\" + txtDelUser.Text + ".txt")
rtbOutput2.Text = "Deleted user: " + txtDelUser.Text
End If
Text file:
admin
guest
testing
Can you either look over my code or give me some code that will allow me to delete from the .txt file, by whats entered into a textbox, without leaving an empty or a way to get rid of the empty line.
Thanks!
You can store the items that you want to write back to file in another list, linesToKeep, like this:
Dim linesToKeep As New List(Of String)
For Each line As String In lines
If Not line.Contains(txtDelUser.Text) Then
linesToKeep.Add(line)
End If
Next
' Write all lines in linesToKeep back to file
For Each line As String In lines
sw.WriteLine(line)
Next
UPDATE:
Here is what the full code should look like using this solution applied to the code posted:
If (txtDelUser.Text = "admin" Or txtDelUser.Text = "guest") Then
rtbOutput2.Text = "You tried to delete: " + txtDelUser.Text + ". But the user is protected by default."
Else
Dim ln As Integer = 1
rtbOutput.Text.First(Of Text = Text.CopyTo.ClipBoard
'Removes the selected username from list of usernames
Dim lines As New List(Of String)
Using sr As New StreamReader("C:\ProgramData\Hax Client\User Data\All Usernames.txt")
While Not sr.EndOfStream
lines.Add(sr.ReadLine)
End While
End Using
' Instead of removing items from the list we read from file
' we are going to keep track of what we want to keep and write back to file later
Dim linesToKeep As New List(Of String)
For Each line As String In lines
If Not line.Contains(txtDelUser.Text) Then
linesToKeep.Add(line)
End If
Next
Dim fs As New FileStream("C:\ProgramData\Hax Client\User Data\All Usernames.txt", FileMode.Append)
Dim sw As New StreamWriter(fs)
' Write all lines in linesToKeep back to file
For Each line As String In lines
sw.WriteLine(line)
Next
sw.Close()
fs.Close()
My.Computer.FileSystem.FileExists("C:\ProgramData\Hax Client\User Data\" + txtDelUser.Text)
My.Computer.FileSystem.DeleteFile("C:\ProgramData\Hax Client\User Data\" + txtDelUser.Text + ".txt")
rtbOutput2.Text = "Deleted user: " + txtDelUser.Text
End If