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
FileInfo
的Length
属性检查文件是否为空,而无需打开它。 - BartoszKPfileInfo.Length
之前尝试fileInfo.Refresh()
。 - Tim SchmelterFileInfo
对象并检查了它的Length
属性并返回0,那么为什么还要使用streamreader
呢?除此之外,您应该将OPTION STRICT
设置为开启状态,因为它可以防止错误。If Not fi.Length.ToString() = 0
无法编译,因为您正在比较字符串和整数。只需检查If fi.Length = 0
即可。 - Tim Schmelter