检查文本文件是否为空

4

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

我有一些问题。基本上我有一个 streamreader 打开一个 .txt 文件,其中目录存储在 'strUsersPath' 中。我试图编写代码,如果文件为空,则执行一项操作,如果文件不为空(有用户),则执行另一项操作。
如果我的 txt 文件中有一个用户,则代码会像预期的那样给出 msgbox("creating normal account"),然而当我没有用户时,它并不会给我其他的 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

检查您的应用程序是否可以打开该文件。 - Epsil0neR
3
你可以使用FileInfoLength属性检查文件是否为空,而无需打开它。 - BartoszKP
@BartoszKP,我忘了提到,我尝试过那个方法,但似乎也不起作用! - user2087008
1
如果那个方法没有起作用,请在检查fileInfo.Length之前尝试fileInfo.Refresh() - Tim Schmelter
@SamCousins:如果您在第一行创建了FileInfo对象并检查了它的Length属性并返回0,那么为什么还要使用streamreader呢?除此之外,您应该将OPTION STRICT设置为开启状态,因为它可以防止错误。If Not fi.Length.ToString() = 0无法编译,因为您正在比较字符串和整数。只需检查If fi.Length = 0即可。 - Tim Schmelter
显示剩余2条评论
2个回答

6
您不需要使用StreamReader。您只需要使用File.ReadAllText函数即可。
If File.ReadAllText(strUsersPath).Length = 0 Then
    MsgBox("File is empty, creating master account")
Else
    MsgBox("Creating normal account")
End If

3
我建议使用这种方法。
If New FileInfo(strUsersPath).Length.Equals(0) Then
    'File is empty.
Else
    'File is not empty.
End If

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接