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

私はいくつかの問題を抱えています。基本的に、ディレクトリが「strUsersPath」に保存されている.txtファイルを開くストリームリーダーがあります。ファイルが空の場合は 1 つのことを実行し、ファイルが空でない場合 (ユーザーが存在する場合) は別のことを実行するように、コードを取得しようとしています。

私の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 に答える