4

我有以下代码:

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

我遇到了一些问题。基本上我有一个流式阅读器打开一个 .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
4

2 回答 2

5

为此,您不需要 StreamReader。所有你需要的是File.ReadAllText

If File.ReadAllText(strUsersPath).Length = 0 Then
    MsgBox("File is empty, creating master account")
Else
    MsgBox("Creating normal account")
End If
于 2014-10-23T19:34:36.370 回答
2

我推荐使用这种方法

If New FileInfo(strUsersPath).Length.Equals(0) Then
    'File is empty.
Else
    'File is not empty.
End If
于 2016-06-26T03:57:43.933 回答