deleting file

jamie123

Well-known member
Joined
May 30, 2008
Messages
82
Programming Experience
Beginner
I'm programming in vb.net using vs2008. Here is my code:

Dim FileToDelete As String
answerlocation = "C:\EBSwiped.ans"
FileToDelete = answerlocation

Do While count < 50 And System.IO.File.Exists(FileToDelete) = False

Threading.Thread.Sleep(200)
FileToDelete = answerlocation
count = count + 1

Loop
Dim sr As New IO.StreamReader(answerlocation)
If System.IO.File.Exists(FileToDelete) = False Then
MsgBox("Please check internet connection.")
Else

Dim objReader As New IO.StreamReader(FileToDelete)
strContents = objReader.ReadLine

If strContents.Substring(1, 1) = "Y" Then
j = 2
Do Until tempvar1 = Chr(34)

approvalcode = approvalcode + tempvar1
tempvar1 = strContents.Substring(j, 1)
j = j + 1

Loop
MsgBox("Accepted")
objReader.Dispose()
objReader.Close()


Else
MsgBox("Card has been rejected")
objReader.Dispose()
objReader.Close()

End If
End If
System.IO.File.Delete(FileToDelete)



This code reads a file downloaded by a credit card processing center, the file contains a letter (Y or N) and a code. The program reads the letter, reports if the credit card was accepted or rejected, then records the code in a variable. To prevent any mistakes in program use, the FileToDelete (EBSwiped.ans) needs to be deleted. The problem is that everytime I try to delete the file ( in code), it says it is being used by another process. I read up a little and made sure I have the .close and .dispose methods but i really don't know what else to do. Any help would be appreciated, thank you!
 
am not sure but.. can u try using else if statements instead of just else? i think its just the if statements

or why dont u close the reader and dispose it after the last END IF just b4 calling the delete function?
 
You're opening the same file twice but only closing it once. Why are you opening two StreamReaders? Why do you have the same file path in two different variables for that matter?

Wherever you can you should ALWAYS use Using blocks to create disposable objects, which guarantees things like closing files:
VB.NET:
Using reader As New StreamReader("file path here")
    'Use reader here.
End Using
The file is automatically closed at the End Using line.
 
Back
Top