Vb.net 检查文本文件是否为空
我有以下代码:Vb.net 检查文本文件是否为空,vb.net,visual-studio,visual-studio-2012,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
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文件,其中目录存储在'strusterspath'中。我试图获取代码,这样如果文件是空的,它会做一件事,如果文件不是空的(有一个用户),那么它会做另一件事
如果我的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
对此,您不需要StreamReader。您只需要
File.ReadAllText
If File.ReadAllText(strUsersPath).Length = 0 Then
MsgBox("File is empty, creating master account")
Else
MsgBox("Creating normal account")
End If
我建议使用这种方法
If New FileInfo(strUsersPath).Length.Equals(0) Then
'File is empty.
Else
'File is not empty.
End If
检查您的应用程序是否可以打开该文件您可以使用
FileInfo
的Length
属性检查文件是否为空,而无需打开它。@BartoszKP我忘了提到,我试过了,但似乎也没用@SamCousins:如果不起作用,请在检查fileInfo.Length
之前尝试。您是否验证了第二种情况下的struerspath
变量内容?您确定该路径中的文件存在且为空吗?可能需要验证属性是否存在。