我想制作一个程序,可以读取和删除驱动器C中的文本文件:我已经能够读取但删除是我的问题。我想在输入正确的用户名和密码后自动删除文本文件。
这是我的代码。当我输入密码和用户名后点击确认按钮。
我尝试了下面的代码,但它说错了。
进程无法访问文件..(“C:\ Users \ smt32 \ Documents \ CP1 FILES \ buzzer \ test.txt“)。因为它正被另一个进程使用
Private Sub btnConfirm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConfirm.Click
Dim user, pass As String
user = (txtUserName.Text)
pass = (txtPass.Text)
If user = "test" And pass = "test" Then
Me.Close()
'Kill("C:\Users\smt32\Documents\CP1 FILES\buzzer\test.txt")
' My.Computer.FileSystem.DeleteFile("C:\Users\smt32\Documents\CP1 FILES\buzzer\test.txt")
System.IO.File.Delete("C:\Users\smt32\Documents\CP1 FILES\buzzer\test.txt")
Else
MsgBox("wrong pass")
End If
End Sub
答案 0 :(得分:0)
阅读后我关闭了我的txtreader。
Public Sub checkTxt()
Try
Dim txtReader As New System.IO.StreamReader("C:\Users\smt32\Documents\CP1 FILES\buzzer\test.txt")
txtAlert.Text = txtReader.ReadToEnd
If txtAlert.Text <> "" Then
playSound()
Timer1.Stop() 'stop the counter if found data
AlertForm.Show()
txtReader.Close()'i add this code so that i can delete
Else
End If
Catch ex As Exception
MsgBox("No file found")
End Try
End Sub
答案 1 :(得分:0)
如果您可以使用File.Delete,如果您已经不打开了要读取的文件(应该测试),那么它是您的代码,它具有打开的句柄。
为了尽可能简单地避免这种情况,请按照建议使用Using..End Using块。
Dim fullText As String
Using r As New System.IO.StreamReader(FileFullPath)
fullText = r.ReadToEnd
End Using
' do something with the full text; the StreamReader has now closed gracefully