检查文本文件是否为空

时间:2013-11-09 00:04:04

标签: vb.net visual-studio visual-studio-2012

我有以下代码:

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

我遇到了一些问题。 Basicaly我有一个streamreader打开一个.txt文件,其中目录存储在'strUsersPath'中。我试图获取代码,以便如果文件为空,它会做一件事,如果文件不为空(有用户),那么它会做另一个。

如果我的txt文件中有用户,代码会按预期提供msgbox(“正常创建帐户”),但是当我没有用户时,它不会给我其他的msgbox,我可以似乎找不到原因。我怀疑是因为IsNullOrWhiteSpace不适合使用它。任何帮助将不胜感激

修改 的 这是我也尝试过的代码,同样的结果,如果已经有用户,点击按钮什么都不做。

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

2 个答案:

答案 0 :(得分:3)

您不需要StreamReader。您所需要的只是File.ReadAllText

If File.ReadAllText(strUsersPath).Length = 0 Then
    MsgBox("File is empty, creating master account")
Else
    MsgBox("Creating normal account")
End If

答案 1 :(得分:0)

我建议使用此方法

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