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
Related
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
Help!!
I have been set this task but i'm really unsure how to do this:
Sub Main()
Dim filePath As String = "C:\...\Projects\testing.txt"
Dim fileHolder As System.IO.StreamReader
Dim line As String
fileHolder = My.Computer.FileSystem.OpenTextFileReader(filePath)
line = fileHolder.ReadLine()
While line <> Nothing
Console.WriteLine(line)
Console.WriteLine("*****")
line = fileHolder.ReadLine()
End While
Console.ReadKey()
End Sub
"Edit the above program so that it only writes lines beginning with “The” to the console. You may find it helpful to revisit the lesson on String Handling to complete this task."
I have tried using if statements inside the while loop or a Do Until loop inside the While one, however this meant it would print the first line that contained "the" and not the third line that also contained "the", as the second line didn't.
Here is the (really bad code) that has failed me so far:
Dim filePath As String = "C:\...\Projects\testing.txt"
Dim fileHolder As System.IO.StreamReader
Dim line As String
fileHolder = My.Computer.FileSystem.OpenTextFileReader(filePath)
line = fileHolder.ReadLine()
Dim the As String = "the"
While line <> Nothing
If line.ToUpper.Contains(the.ToUpper) Then
Console.WriteLine(line)
Console.WriteLine("*****")
line = fileHolder.ReadLine()
End If
End While
Console.ReadKey()
Thank you for any help!!
Try this:
Dim filePath As String = "C:\...\Projects\testing.txt"
Dim fileHolder As System.IO.StreamReader
Dim line As String
fileHolder = My.Computer.FileSystem.OpenTextFileReader(filePath)
line = fileHolder.ReadLine()
Dim the As String = "the"
While line <> Nothing
If line.ToUpper.Contains(the.ToUpper) Then
Console.WriteLine(line)
Console.WriteLine("*****")
End If
line = fileHolder.ReadLine()
End While
Console.ReadKey()
So I'm trying to generate a random number on button click. Now this number needs to be between two numbers that are inside my text file with various other things all separated by the "|" symbol. The number is then put into the text of a textbox which is being created after i run the form. I can get everything to work perfectly once, but as soon as i try to generate a different random number it gives me the error: "Index was out of range, must be non-negative and less than the size of the collection." Here is the main code as well as the block that generates the textbox after loading the form. As well as the contents of my text file.
Private Sub generate()
Dim newrandom As New Random
Try
Using sr As New StreamReader(itemfile) 'Create a stream reader object for the file
'While we have lines to read in
Do Until sr.EndOfStream
Dim line As String
line = sr.ReadLine() 'Read a line out one at a time
Dim tmp()
tmp = Split(line, "|")
rows(lineNum).buybutton.Text = tmp(1)
rows(lineNum).buyprice.Text = newrandom.Next(tmp(2), tmp(3)) 'Generate the random number between two values
rows(lineNum).amount.Text = tmp(4)
rows(lineNum).sellprice.Text = tmp(5)
rows(lineNum).sellbutton.Text = tmp(1)
lineNum += 1
If sr.EndOfStream = True Then
sr.Close()
End If
Loop
End Using
Catch x As Exception ' Report any errors in reading the line of code
Dim errMsg As String = "Problems: " & x.Message
MsgBox(errMsg)
End Try
End Sub
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
rows = New List(Of duplicate)
For dupnum = 0 To 11
'There are about 5 more of these above this one but they all have set values, this is the only troublesome one
Dim buyprice As System.Windows.Forms.TextBox
buyprice = New System.Windows.Forms.TextBox
buyprice.Width = textbox1.Width
buyprice.Height = textbox1.Height
buyprice.Left = textbox1.Left
buyprice.Top = textbox1.Top + 30 * dupnum
buyprice.Name = "buypricetxt" + Str(dupnum)
Me.Controls.Add(buyprice)
pair = New itemrow
pair.sellbutton = sellbutton
pair.amount = amounttxt
pair.sellprice = sellpricetxt
pair.buybutton = buybutton
pair.buyprice = buypricetxt
rows.Add(pair)
next
end sub
'textfile contents
0|Iron Sword|10|30|0|0
1|Steel Sword|20|40|0|0
2|Iron Shield|15|35|0|0
3|Steel Shield|30|50|0|0
4|Bread|5|10|0|0
5|Cloak|15|30|0|0
6|Tent|40|80|0|0
7|Leather Armour|50|70|0|0
8|Horse|100|200|0|0
9|Saddle|50|75|0|0
10|Opium|200|500|0|0
11|House|1000|5000|0|0
Not sure what else to add, if you know whats wrong please help :/ thanks
Add the following two lines to the start of generate():
Private Sub generate()
Dim lineNum
lineNum = 0
This ensures that you don't point to a value of lineNum outside of the collection.
I usually consider it a good idea to add
Option Explicit
to my code - it forces me to declare my variables, and then I think about their initialization more carefully. It helps me consider their scope, too.
Try this little modification.
I took your original Sub and changed a little bit take a try and let us know if it solve the issue
Private Sub generate()
Dim line As String
Dim lineNum As Integer = 0
Dim rn As New Random(Now.Millisecond)
Try
Using sr As New StreamReader(_path) 'Create a stream reader object for the file
'While we have lines to read in
While sr.Peek > 0
line = sr.ReadLine() 'Read a line out one at a time
If Not String.IsNullOrEmpty(line) And Not String.IsNullOrWhiteSpace(line) Then
Dim tmp()
tmp = Split(line, "|")
rows(lineNum).buybutton.Text = tmp(1)
rows(lineNum).buyprice.Text = rn.Next(CInt(tmp(2)), CInt(tmp(3))) 'Generate the random number between two values
rows(lineNum).amount.Text = tmp(4)
rows(lineNum).sellprice.Text = tmp(5)
rows(lineNum).sellbutton.Text = tmp(1)
lineNum += 1
End If
End While
End Using
Catch x As Exception ' Report any errors in reading the line of code
Dim errMsg As String = "Problems: " & x.Message
MsgBox(errMsg)
End Try
End Sub
I'm currently using the following to read the contents of all text files in a directory into an array
Dim allLines() As String = File.ReadAllLines(txtfi.FullName)
Within the text files are only 6 lines that all follow the same format and will read something like
forecolour=black
I'm trying to then search for the word "forecolour" and retrieve the information after the "=" sign (black) so i can then populate the below code
AllDetail(numfiles).uPath = ' this needs to be the above result
I've only posted parts of the code but if it helps i can post the rest. I just need a little guidance if possible
Thanks
This is the full code
Dim numfiles As Integer
ReDim AllDetail(0 To 0)
numfiles = 0
lb1.Items.Clear()
Dim lynxin As New IO.DirectoryInfo(zMailbox)
lb1.Items.Clear()
For Each txtfi In lynxin.GetFiles("*.txt")
Dim allLines() As String = File.ReadAllLines(txtfi.FullName)
ReDim Preserve AllDetail(0 To numfiles)
AllDetail(numfiles).uPath = 'Needs to be populated
AllDetail(numfiles).uName = 'Needs to be populated
AllDetail(numfiles).uCode = 'Needs to be populated
AllDetail(numfiles).uOps = 'Needs to be populated
lb1.Items.Add(IO.Path.GetFileNameWithoutExtension(txtfi.Name))
numfiles = numfiles + 1
Next
End Sub
AllDetail(numfiles).uPath = Would be the actual file path
AllDetail(numfiles).uName = Would be the detail after “unitname=”
AllDetail(numfiles).uCode = Would be the detail after “unitcode=”
AllDetail(numfiles).uOps = Would be the detail after “operation=”
Within the text files that are being read there will be the following lines
Unitname=
Unitcode=
Operation=
Requirements=
Dateplanned=
For the purpose of this array I just need the unitname, unitcode & operation. Going forward I will need the dateplanned as when this is working I want to try and work out how to only display the information if the dateplanned matches the date from a datepicker. Hope that helps and any guidance or tips are gratefully received
If your file is not very big you could simply
Dim allLines() As String = File.ReadAllLines(txtfi.FullName)
For each line in allLines
Dim parts = line.Split("="c)
if parts.Length = 2 andalso parts(0) = "unitname" Then
AllDetails(numFiles).uName = parts(1)
Exit For
End If
Next
If you are absolutely sure of the format of your input file, you could also use Linq to remove the explict for each
Dim line = allLines.Where(Function(x) (x.StartsWith("unitname"))).SingleOrDefault()
if line IsNot Nothing then
AllDetails(numFiles).uName = line.Split("="c)(1)
End If
EDIT
Looking at the last details added to your question I think you could rewrite your code in this way, but still a critical piece of info is missing.
What kind of object is supposed to be stored in the array AllDetails?
I suppose you have a class named FileDetail as this
Public class FileDetail
Public Dim uName As String
Public Dim uCode As String
Public Dim uCode As String
End Class
....
numfiles = 0
lb1.Items.Clear()
Dim lynxin As New IO.DirectoryInfo(zMailbox)
' Get the FileInfo array here and dimension the array for the size required
Dim allfiles = lynxin.GetFiles("*.txt")
' The array should contains elements of a class that have the appropriate properties
Dim AllDetails(allfiles.Count) as FileDetail
lb1.Items.Clear()
For Each txtfi In allfiles)
Dim allLines() As String = File.ReadAllLines(txtfi.FullName)
AllDetails(numFiles) = new FileDetail()
AllDetails(numFiles).uPath = txtfi.FullName
Dim line = allLines.Where(Function(x) (x.StartsWith("unitname="))).SingleOrDefault()
if line IsNot Nothing then
AllDetails(numFiles).uName = line.Split("="c)(1)
End If
line = allLines.Where(Function(x) (x.StartsWith("unitcode="))).SingleOrDefault()
if line IsNot Nothing then
AllDetails(numFiles).uName = line.Split("="c)(1)
End If
line = allLines.Where(Function(x) (x.StartsWith("operation="))).SingleOrDefault()
if line IsNot Nothing then
AllDetails(numFiles).uOps = line.Split("="c)(1)
End If
lb1.Items.Add(IO.Path.GetFileNameWithoutExtension(txtfi.Name))
numfiles = numfiles + 1
Next
Keep in mind that this code could be really simplified if you start using a List(Of FileDetails)
I have the following code;
Public Sub writetofile()
' 1: Append playername
Using writer As StreamWriter = New StreamWriter("highscores.txt", True)
writer.WriteLine(PlayerName)
End Using
' 2: Append score
Using writer As StreamWriter = New StreamWriter("highscores.txt", True)
writer.WriteLine(Score)
End Using
End Sub
What I now want to do is read all the odd lines of the file (the player names) and the even lines into two separate list boxes, how would I go about that??
I need to modify;
Using reader As StreamReader = New StreamReader("file.txt")
' Read one line from file
line = reader.ReadLine
End Using
I have used one of the following solutions but cannot get it working :(
Public Sub readfromfile()
Using reader As New StreamReader("scores.txt", True)
Dim line As Integer = 0
While Not reader.EndOfStream
If line Mod 2 = 0 Then
frmHighScores.lstScore.Items.Add(line)
Else
frmHighScores.lstScore.Items.Add(line)
End If
line += 1
End While
End Using
End Sub
You can use the Mod operator for this:
Using reader As New StreamReader("highscores.txt", True)
Dim line As Integer = 0
Dim text As String
Do
text = reader.ReadLine()
If text = Nothing Then
Exit Do
End If
If line Mod 2 = 0 Then
''# even line
Else
''# odd line
End If
line += 1
Loop
End Using
This approach also works for cases when it's not an even/odd pattern, but another number of repetions. Say you have 3 lines for each player:
player name 1
score 1
avatar url 1
player name 2
score 2
avatar url 2
...
Then you can get this pattern by using Mod with 3
Dim subLine As Integer = line Mod 3
If subLine = 0 Then
''# player name
ElseIf subLine = 1 Then
''# score
Else
''# avatar url
End If
line += 1
If you can reliably expect there to be an even number of lines in the file, then you can simplify this by reading two at a time.
Using reader As StreamReader = New StreamReader("file.txt")
While Not reader.EndOfStream
Dim player as String = reader.ReadLine()
Dim otherInfo as String = reader.ReadLine()
'Do whatever you like with player and otherInfo
End While
End Using
I don't really know the syntax of VB but something like this:
dim odd as boolean = True
Using reader As StreamReader = New StreamReader("file.txt")
line = reader.ReadLine
if odd then
' add to list A
else
' add to list B
end
odd = Not Odd
End Using
Another possibility is to just read the whole file as a block into a single string and the SPLIT the string on vbcrlf
Dim buf = My.Computer.FileSystem.ReadAllText(Filename)
Dim Lines() = Split(Buf, vbcrlf)
Then, lines will contain all the lines from the file, indexed.
So you could step through them to get each player and his other info.
For x = 0 to ubound(Lines)
'do whatever with each line
next
If the file was HUGE, you wouldn't necessarily want to do it this way, but for small files, it's a quick and easy way to handle it.