user2087008
user2087008

Reputation:

Checking if text file is empty

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

Upvotes: 4

Views: 18431

Answers (2)

mikro
mikro

Reputation: 525

I recommend using this method

If New FileInfo(strUsersPath).Length.Equals(0) Then
    'File is empty.
Else
    'File is not empty.
End If

Upvotes: 3

Chad
Chad

Reputation: 1549

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

Upvotes: 6

Related Questions