Counting each line in a textfile - vb.net

So I'm a bit stuck with this. Basically I've got a text file in a directory and in that text file, I've added different text in each of its line. I'm trying to use this to count how many lines there are in that text file. I'm using IsolatedStorageFile to do this and this is how I'm accessing it.
So far I've got this but It's not working:
Using isoComments As IsolatedStorageFileStream = New IsolatedStorageFileStream("textfile1.txt", FileMode.Open, isoStore)
Using readerComments As StreamReader = New StreamReader(isoComments)
For Each line In readerComments.ReadLine
MessageBox.Show(line.ToString.Count)
Next
End Using
End Using
The result is not the amount of lines instead, the amount of characters in each line. This is not what I want I want the number of lines in that particular textfile. Is anyone able to help me with this.

Something like this:
Dim iLineCount As Integer
iLineCount = 0
Using isoComments As IsolatedStorageFileStream =
New IsolatedStorageFileStream("textfile1.txt", FileMode.Open, isoStore)
Using readerComments As StreamReader = New StreamReader(isoComments)
For Each line In readerComments.ReadLine
iLineCount=iLineCount+1
Next
MessageBox.Show(iLineCount)
End Using
End Using

So I managed to solve this problem. My original idea was to get the amount of times a textfile was edited and so I figured adding something in each line of that textfile and counting each line would help but i couldn't find a way to it.
What I did was I added a counter which increases by 1 everytime it saves and then when it's read +1 is added to it. That way I have an exact number of times it was edited because everytime the textfile is edited, like mentioned before, it increases like a counter by 1. so if the user edited the textfile about 12 times then there will be the number 12 in the file and that will be read when the ser decides to edit the textfile again, once he saves +1 to the 12 will be added maing it 13.
I used this method to do the increment by one:
Using isoStream As IsolatedStorageFileStream = New IsolatedStorageFileStream("textfile.text", FileMode.CreateNew, isoStore) Using writer As StreamWriter = New StreamWriter(isoStream)
Dim i As Integer
i += 1
writer.WriteLine(i)
End Using
End Using

Related

Write to a text file while is it open and visible

I'm sure this is really simple, but has had me stumped for a while!
I need to show the user a text file, with lines being written to it as my program executes. Stuff like "Working on this file - Successful!". Another forum thread has helped me to allow the text file to be accessed by multiple processes, but now when I open the text file using Process.Start, it doesn't show the lines that are being written using the StreamWriter. Any help very much appreciated.
Code:
Dim ExportLog As String = "C:\ExportLog.txt"
If System.IO.File.Exists(ExportLog) Then
System.IO.File.Delete(ExportLog)
End If
Using writeStream = System.IO.File.Open(ExportLog,
FileMode.OpenOrCreate, FileAccess.ReadWrite,
FileShare.ReadWrite), Write As New StreamWriter(writeStream)
Write.WriteLine("Starting")
End Using
Dim MyLog As Process = Process.Start(ExportLog)

Simple File I/O in Visual Basic 2013

I want to learn how to write and read data from files using Visual Basic Studio Express 2013 for Windows Desktop.
Specifically, I have a class called Pilots. The class includes text of a first and last name, and integers representing rank, skill, missions and status.
There is an ArrayList called Squadron that contains 18 (at start) Pilots.
What I want to do is save and then load all the data in Squadron to a file. And I'm not sure how to get it to work properly. I've read numerous books and sites, but somewhere along the line, I'm just not comprehending how to get it to work correctly.
At this point, I've been able to write the data to a file.... but I'm having no luck getting it back out of the file.
To write it out... I'm using this code:
Dim currentpilot As New Pilot("John", "Doe")
' Create the BinaryWriter and use File.Open to create the file.
Using writer As BinaryWriter = New BinaryWriter(File.Open("squadron.dat", FileMode.Create))
' Write each integer.
writer.Write(SquadronList.Count)
For index = 0 To SquadronList.Count - 1
currentpilot = CType(SquadronList(index), Pilot)
writer.Write(currentpilot.pFirstName)
writer.Write(currentpilot.pLastName)
writer.Write(currentpilot.pSkill)
writer.Write(currentpilot.pRank)
writer.Write(currentpilot.pStatus)
writer.Write(currentpilot.pMissions)
writer.Write(currentpilot.pKills)
Next
End Using
The writer.Write(SquadronList.Count) line is there to record the number of actual Pilot records in the file. I don't know if that's necessary or not.
The file does write to disk and just looking at it with notepad, it does seem to have the correct data.
The problem is getting it back out. This code fails quickly...
Using reader As BinaryReader = New BinaryReader(File.OpenRead("squadron.dat"))
Dim index As Integer = reader.ReadInt32
For counter = 0 To index - 1
currentpilot.pFirstName = reader.ReadString
currentpilot.pLastName = reader.ReadString
currentpilot.pSkill = reader.ReadInt16
currentpilot.pRank = reader.ReadInt16
currentpilot.pStatus = reader.ReadInt16
currentpilot.pMissions = reader.ReadInt16
currentpilot.pKills = reader.ReadInt16
SquadronList.Add(currentpilot)
Next
End Using
So... any suggestions or guidance will be appreciated!

How to make a console app read different lines from a text file?

So I was just playing around with VB console apps and was wondering how to read a single text file but read the separate lines. In my example, I'm playing around with a credential storage containing fake data as in the form of a username and password. I'm not worried about encrypting anything as of yet but as my question states, how to make the app read line 1 for username for site a, line 2 as password for site a etc. Sorry if I'm not too clear, I can elaborate further if need be.
Well supposing that your text file is composed by repeating lines where the odd ones are the usernames and the even ones are the passwords then
Dim lines() as String = File.ReadAllLines("FileName.txt")
if (lines.Length MOD 2) <> 0 Then
Console.WriteLine("Lines not even")
Else
For i = 0 to lines.Length - 1 Step 2
Console.WriteLine("User={0} with password={1}", lines(i), lines(i+1))
Next
End If
This works only if the number of lines in the files is exactly even
If the file contains alternating lines of username and password, then this should do:
Using file As FileStream = New FileStream(path, ...other constructor options...)
Using reader As StreamReader = New StreamReader(file)
While Not reader.EndOfStream
username = reader.ReadLine
password = reader.ReadLine
End While
End Using
End Using
Of course everything must line up perfectly for this to work - and nothing is ever that perfect.

[VB.NET]Transferring data from 1 file to another

Basically I want to take My Client.
Then for example Lets say in my client I have "A = 1"
Then my 2nd file which has random data in it.
So Client= My Client
File = The File which I want in the end result
How could I Inject "A = TextBox1.Text" from Client to File.
I heard it's called "End Of File" or something like that.
Any help please?
Use System.IO.File in combination with StreamWriter.
File.CreateFile() helps you create files. Check if the following sample helps you (This is not written to solve your exact expectation, but gives you the idea of available options)
Dim fs as new FileStream("YourFile.bin", FileMode.Create)
Dim writer as New BinaryWriter(fs)
For i as Integer = 0 To 10
writer.Write(CInt(i))
Next
writer.Close()
fs.Close()
FileStream.CreateText() method helps you create a Text stream and you can use this to write your textbox content into file.

Avoiding 'End Of File' errors

I'm trying to import a tab delimited file into a table.
The issue is, SOMETIMES, the file will include an awkward record that has two "null values" and causes my program to throw a "unexpected end of file".
For example, each record will have 20 fields. But the last record will have only two fields (two null values), and hence, unexpected EOF.
Currently I'm using a StreamReader.
I've tried counting the lines and telling bcp to stop reading before the "phantom nulls", but StreamReader gets an incorrect count of lines due to the "phantom nulls".
I've tried the following code to get rid of all bogus code (code borrowed off the net). But it just replaces the fields with empty spaces (I'd like the result of no line left behind).
Public Sub RemoveBlankRowsFromCVSFile2(ByVal filepath As String)
If filepath = DBNull.Value.ToString() Or filepath.Length = 0 Then Throw New ArgumentNullException("filepath")
If (File.Exists(filepath) = False) Then Throw New FileNotFoundException("Could not find CSV file.", filepath)
Dim tempFile As String = Path.GetTempFileName()
Using reader As New StreamReader(filepath)
Using writer As New StreamWriter(tempFile)
Dim line As String = Nothing
line = reader.ReadLine()
While Not line Is Nothing
If Not line.Equals(" ") Then writer.WriteLine(line)
line = reader.ReadLine()
End While
End Using
End Using
File.Delete(filepath)
File.Move(tempFile, filepath)
End Sub
I've tried using SSIS, but it encounters the EOF unexpected error.
What am I doing wrong?
If you read the entire file into a string variable (using reader.ReadToEnd()) do you get the whole thing? or are you just getting the data up to those phantom nulls?
Have you tried using the Reader.ReadBlock() function to try and read past the file length?
At our company we do hundreds of imports every week. If a file is not sent in the correct, agreed to format for our automated process, we return it to the sender. If the last line is wrong, the file should not be processed because it might be missing information or in some other way corrupt.
One way to avoid the error is to use ReadAllLines, then process the array of file lines instead of progressing through the file. This is also a lot more efficient than streamreader.
Dim fileLines() As String
fileLines = File.ReadAllLines("c:\tmp.csv")
...
for each line in filelines
If trim(line) <> "" Then writer.WriteLine(line)
next line
You can also use save the output lines in the same or a different string array and use File.WriteAllLines to write the file all at once.
You could try the built-in .Net object for reading tab-delimited files. It is Microsoft.VisualBasic.FileIO.TextFileParser.
This was solved using a bit array, checking one bit at a time for the suspect bit.