1,105,456 Community Members

Unable to delete file get file in use error :(

Member Avatar
jackfriendstie
Newbie Poster
2 posts since Aug 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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
Member Avatar
kingsonprisonic
Posting Whiz in Training
265 posts since Nov 2009
Reputation Points: 42 [?]
Q&As Helped to Solve: 54 [?]
Skill Endorsements: 0 [?]
 
0
 
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)'Here is the mistake

you try to delete a file before closing the file reader.
So first close it.

objReader.Dispose()

Then Kill it

Ok.

Member Avatar
jackfriendstie
Newbie Poster
2 posts since Aug 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Thank you :)

Member Avatar
kingsonprisonic
Posting Whiz in Training
265 posts since Nov 2009
Reputation Points: 42 [?]
Q&As Helped to Solve: 54 [?]
Skill Endorsements: 0 [?]
 
0
 

This Thread is SOLVED

Member Avatar
codeorder
Postaholic
2,027 posts since Aug 2010
Reputation Points: 197 [?]
Q&As Helped to Solve: 390 [?]
Skill Endorsements: 10 [?]
 
0
 

See if this helps.

Public Class Form1
    Private myFile As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\New.txt"
    Private arFileContent() As String = Nothing

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If File.Exists(myFile) Then
            arFileContent = File.ReadAllLines(myFile) '// load file lines into Array.
            Kill(myFile) '// delete file.
            MsgBox(arFileContent(0)) '// FOR TESTING, READ LINE 1.
        End If
    End Sub
End Class
You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: