Question Unable to delete file get file in use error :(

jackfriendstie

New member
Joined
Aug 31, 2011
Messages
1
Programming Experience
5-10
What I want, is for my text file to be read into the array named "CFiles()". Then once this is complete to delete the file

But

I get the error, The process cannot access the file 'C:\Users\Andrew\Desktop\New.txt' because it is being used by another process. On 3rd to last line.

My code is below:

Public Class Form1
Dim File As String = "C:\Users\Andrew\Desktop\New.txt"
Dim CFiles() As String
Dim EndCFiles As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If System.IO.File.Exists(File) = True Then



Dim objReader As New System.IO.StreamReader(File)

Do While objReader.Peek() <> -1
ReDim Preserve CFiles(EndCFiles)
CFiles(EndCFiles) = CFiles(EndCFiles) & objReader.ReadLine()
EndCFiles = EndCFiles + 1
Loop

End If
Kill(File)
End Sub
End Class



What can I do to get this working?
 
Try This (You have another problem in your code: You are deleting the file weather it existed or not). :

Public Class Form1
Dim File As String = "C:\Users\Andrew\Desktop\New.txt"
Dim CFiles() As String
Dim EndCFiles As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If System.IO.File.Exists(File) = True Then



Dim objReader As New System.IO.StreamReader(File)

Do While objReader.Peek() <> -1
ReDim Preserve CFiles(EndCFiles)
CFiles(EndCFiles) = CFiles(EndCFiles) & objReader.ReadLine()
EndCFiles = EndCFiles + 1
Loop
objReader.Close
'The Following Line Is Not Necessary :
objReader.Dispose
Kill(File)
End If

End Sub
End Class.

Hope it helps!
 
if your just reading the text into a variable you could just do this...

VB.NET:
Dim i As String = FileIO.FileSystem.ReadAllText("C:\Users\Home\Desktop\test.txt")
MsgBox(i)

otherwise ya... you need to .close or .dispose the streamreader before killing the file

take care.
 
Back
Top