Checking if text file is empty - vb.net

I have the following code:
Private Sub btnCreateAccount_Click(sender As Object, e As EventArgs) Handles btnCreateAccount.Click
Dim fi As New System.IO.FileInfo(strUsersPath)
Using r As StreamReader = New StreamReader(strUsersPath)
Dim line As String
line = r.ReadLine ' nothing happens after this point
Do While (Not line Is Nothing)
If String.IsNullOrWhiteSpace(line) Then
MsgBox("File is empty, creating master account")
Exit Do
Else
MsgBox("Creating normal account")
End If
line = r.ReadLine
Loop
End Using
End Sub
I am having some problems. Basicaly I have a streamreader opening up a .txt file where the directory is stored in 'strUsersPath'. I am trying to get the code so that if the file is empty, it does one thing, and if the file is not empty (there is a user) then it does another.
If I have a user in my txt file, the code gives the msgbox("creating normal account"), as expected, however when I do not have a user, it does not give me the other msgbox, and I can't seem to work out why. I suspect it is because IsNullOrWhiteSpace is not the right thing to use for this. Any help would be greatly appreciated
EDIT
This is the code I have also tried, same result, clicking the button does nothing if there is already a user.
Private Sub btnCreateAccount_Click(sender As Object, e As EventArgs) Handles btnCreateAccount.Click
Dim fi As New System.IO.FileInfo(strUsersPath)
Using r As StreamReader = New StreamReader(Index.strUsersPath)
Dim line As String
line = r.ReadLine ' nothing happens after this point
Do While (Not line Is Nothing)
fi.Refresh()
If Not fi.Length.ToString() = 0 Then
MsgBox("File is empty, creating master account") ' does not work
Exit Do
Else
MsgBox("Creating normal account") ' works as expected
End If
line = r.ReadLine
Loop
End Using
End Sub

You do not need a StreamReader for this. All you need is File.ReadAllText
If File.ReadAllText(strUsersPath).Length = 0 Then
MsgBox("File is empty, creating master account")
Else
MsgBox("Creating normal account")
End If

I recommend using this method
If New FileInfo(strUsersPath).Length.Equals(0) Then
'File is empty.
Else
'File is not empty.
End If

Related

Read in values from comma delimited text file and add,create object of the class, then add objects to collection

I currently have the following code:
Public Class CPUForm
Dim myCPUList As New List(Of CPUClass)
Dim Counter As Integer = 0
Private Sub CPUForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
OpenFileDialog.ShowDialog()
Try
If IO.File.Exists(OpenFileDialog.FileName) = False Then
End If
Catch ex As IO.FileNotFoundException
MessageBox.Show("The File Could Not Be Found", "Alert")
End Try
If IO.File.Exists(OpenFileDialog.FileName) = True Then
Dim sr As IO.StreamReader = IO.File.OpenText(OpenFileDialog.FileName)
Dim line As Object
Dim data() As Object
Do Until sr.EndOfStream
line = sr.ReadLine
data = line.Split(",")
Dim ACpu As New CPUClass(data(0), data(1), data(2), data(3), data(4), data(5))
myCPUList(Counter) = ACpu
Counter += 1
Loop
sr.Close()
End If
lstOut.DataSource = Nothing
lstOut.DataSource = myCPUList
End Sub
End Class
The goal here is to read-in values from a comma separated text file, create objects of the class, add those objects to the collection, and then display the collection in a listbox using an overridden ToString method.
Right now I get no errors, even at runtime. The problem is that one the file is selected, nothing happens. Nothing is displayed in the listbox as if nothing was added to the collection. Also, an overloaded constructor exists to receive the values being read in.
Turns out the code is fine, the problem was an out of place comma in the text file.

Error with VB ParseFileText method

When I run this I made a dummy "Button1" to test populate the fields they will successfully fill out the texts boxes. How ever I will have it parse that file every minute, and when I do it again I get the error shown below. By adding the routine "DisplayForm_Load" to the button1_click even it would work fine.
My question is I'm pretty sure I shouldn't have to redefine this every time? I think I'm not setting the index back to 0 or something along those lines. From what I've been able to understand from MS website is its like its indexing things in the array that don't exist.
Error received:
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in WindowsApplication4.exe
Imports Microsoft.VisualBasic.FileIO
Public Class Form1
Private Directory As String ' Used to hold the folder directory to push/pull data from.
Private FileParser As Microsoft.VisualBasic.FileIO.TextFieldParser
Private Sub PushButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles PushButton.Click
' Sends information to txt file.
' This bit works fine, just writes code to txt file that can be parsed below.
End Sub
Sub DefineTextFieldParse_Load() Handles MyBase.Load
' Instantiate teh TextFieldParser and the set the delimiter
Dim FileName As String = "C:\Users\Caleb\Documents\TestDoc.txt"
Try
FileParser = New FileIO.TextFieldParser(FileName) '' Selects File to Parse
FileParser.TextFieldType = FieldType.Delimited
FileParser.SetDelimiters(",")
Catch ex As Exception
' Errors
MessageBox.Show("Unable to read the file" & "," & FileName)
End Try
End Sub
Sub UpdateCheck()
' Checks share txt file for update.
Dim FileName As String = "C:\Users\<Me>\Documents\TestDoc.txt"
Dim FieldString() As String
'Read the file
If Not FileParser.EndOfData Then
FieldString = FileParser.ReadFields()
' 1st Field
NIS1TextBox.Text = FieldString(0)
' 2nd Field
NIS2TextBox.Text = FieldString(1)
' You get the idea...All Testboxes identified above in the write section
' Repeats 12 more times...
EODTextBox.Text = FieldString(14)
InfoRichTextBox.Text = FieldString.LastOrDefault()
End If
End Sub
Sub PushUpdate()
End Sub
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
'DefineTextFieldParse_Load()_Load() ' When Enabled code works fine when commented out generates alert.
UpdateCheck()
End Sub
End Class
mchihinney - I did review https://msdn.microsoft.com/en-us/library/hks5e2k6.aspx
However what I found was the issue was with the formatting of the text file. The problem I found was with the text file there was a second line which was blank, so when it tried to parse nothing it through the error. Deleting the second line from the .txt file and worked as expected.

Listview multi lines

I created a program to load a text file, should load all lines from the textfile and display them in the listview
However It only loads the first line in the listview how do I get it to read the entire file?
Sub Loadbtn_Click(sender As System.Object, e As System.EventArgs) Handles Browse.Click
OpenFD.ShowDialog()
Dim Path As String = OpenFD.FileName
Dim AllItems As String
Try
AllItems = My.Computer.FileSystem.ReadAllText(Path)
Dim ItemLines As New TextBox
ItemLines.Text = AllItems
Dim lv As New ListViewItem
For Each Line As String In ItemLines.Lines
List.Items.Add(lv)
lv.Text = Line
lv.SubItems.Add(Crypto.AES_Decrypt(Line))
Next
Catch ex As Exception
End Try
End Sub
One possible solution could look like this:
Sub Loadbtn_Click(sender As System.Object, e As System.EventArgs) Handles Browse.Click
OpenFD.ShowDialog()
' full path to the file + name
Dim filename As String = OpenFD.FileName
Try
' check if file exists to prevent errors
if (File.Exists(filename)) then
' fetch complete text into as lines
Dim Lines = File.ReadAllLines(filename)
' iterate over each line
For Each Line As String In Lines
Dim lv as new ListViewItem
' take it
lv.Text = Line
' and use it
lv.SubItems.Add(Crypto.AES_Decrypt(Line))
' show it
List.Items.Add(lv)
Next
end if
Catch ex As Exception
' inform the user resp. developer
Console.WriteLine(String.Format("An error occurred: {0}", ex.Message))
End Try
End Sub
As already mentioned use File.ReadAllLines if you want to read the file line by line and don't suppress errors - inform the user or at least the developer (yourself, using a log file or something appropriate).

Object reference not set to an instance of an object in Visual Studio 2010

I am trying to make a program that takes a text from a file and writes it into a label in visual studios 10. I want to be able to click buttons on the exe to make it go from the previous line to the next line and vise versa. I am storing the text into an array and then making the label equal the text on the given part of the array. I am receiving the error "Object reference not set to an instance of an object." Can anyone help ? thanks. here is part of my code my code:
Private Sub BrowseButton_Click(sender As System.Object, e As System.EventArgs) Handles BrowseButton.Click
Dim UserInput As DialogResult = Browser.ShowDialog()
If UserInput = Windows.Forms.DialogResult.Cancel Then
Return
End If
FileOpen(1, Browser.FileName, OpenMode.Input)
Do While Not EOF(1)
Input(1, InternalTextFile(Index))
Index += 1
Loop
FileClose(1)
Output1Text.Text = InternalTextFile(Index)
Output2Text.Text = InternalTextFile(Index + 1)
End Sub
The error arises On the line Input(1, InternalTextFile(Index))
Without seeing more code it's hard to tell, but if the error is on Input(1, InternalTextFile(Index)), its likely that the variable InternalTextFile was never assigned a value. Something like this maybe?
Dim InternalTextFile As New List(of String)
Dim reader As StreamReader = New StreamReader(Browser.FileName)
Try
Do
InternalTextFile.Add(reader.ReadLine)
Loop Until reader.Peek = -1
Finally
reader.Close()
End Try
It looks like maybe you want something like this:
Private Sub BrowseButton_Click(sender As System.Object, e As System.EventArgs) Handles BrowseButton.Click
If Browser.ShowDialog() = Windows.Forms.DialogResult.Cancel Then Exit Sub
Dim InternalTextFile() As String = File.ReadAllLines(Browser.FileName)
Output1Text.Text = InternalTextFile(InternalTextFile.Length - 2)
Output2Text.Text = InternalTextFile(InternalTextFile.Length - 1)
End Sub

Populating a combo box with the first word of a textfile

So I feel like im pretty close, but I also have a feeling I am mixing up StreamReader and ReadAllLines
....................................................................................
Option Strict On
Imports System.IO
Public Class Form4
Dim file As System.IO.StreamWriter
Private Sub Form4_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
file = My.Computer.FileSystem.OpenTextFileWriter("c:\devices.bat", False)
file.WriteLine("#echo off")
file.WriteLine("cd " & Form1.TextBox2.Text)
file.WriteLine("adb devices > C:\devices.txt")
file.Close()
Shell("C:\devices.bat", AppWinStyle.Hide, True, 500)
Dim output() = System.IO.File.ReadAllLines("C:\deviceinfo2.txt")
Dim Devices As String = ""
Dim line() As String = {}
For X = 1 To output.Count = -1
line = output(X).Split(New Char() {(" ")})
Devices = line(0)
ComboBox1.Items.Add(Devices)
Next
output.Close()
output.Dispose()
End Sub
End Class
........................................................................
What I am trying to have it do is to start reading on line two of devices.txt and then read the first word from each line until the text file is done.
It seems simple enough, but like I said, I think I am mixing streamreader with readalllines
Any help is appreciated
Class Test
Public Sub Main()
Try
' Create an instance of StreamReader to read from a file.
' The using statement also closes the StreamReader.
Using sr As New StreamReader("TestFile.txt")
Dim line, firstWord As String
Dim i as Integer = 0
' Read and display lines from the file until the end of
' the file is reached.
Do
line = sr.ReadLine()
If Not (line Is Nothing) AndAlso i > 0 Then
firstWord = line.Split(" ")(i)
'do your logic
End If
i += 1
Loop Until line Is Nothing
End Using
Catch e As Exception
' Let the user know what went wrong.
End Try
End Sub
End Class
Grabbed this from MSDN and modified it. It should compile, but I didn't test it. This will loop through the lines, 1 by 1, skip the first line and grab each line's first word after. Hope this helps.