FileIOExcepion when trying to delete a file for the second time

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I try to delete a file in a for each loop. My code checks if the file exists
and if it does, it will delete the file and create a new file with the same
name.
The first time it works perfect, but the second time it gives me a
FileIOException. I want to prevent this from happening. What can i do to make
sure the file isn't in use anymore the second time i try to delete it?

for each dr in table.rows
if file.exist("C:\sample.txt") then
file.delete("C:\sample.txt")
dim sw as new streamwriter("C:\sample.txt")
sw.writeline(MyString)
sw.close
else
dim sw as new streamwriter("C:\sample.txt")
sw.writeline(MyString)
sw.close
end if
 
Hi Huahe,

As you seem to be deleting the file you created a split second earlier I suspect the file isn't fully created yet, only buffered for creation. This isn't normally an issue since it should be created soon enough, but when you do tight loops like that you may bump into this. This is also a reason why for instance MS Sql Server uses unbuffered IO operations since it needs to know for sure that the data has been changed on the harddrive, and not just cached for change at a later time.
 
Thank you for your answer Morten. I understand now why it doesn't work. But
do you know a solution for my problem?
Can i maybe pause the loop for a moment? Or make sure the file is created
before i go further with my program execution.
 
The solution depends on what you are trying to do. It may be that you don't have to use a file at all.

Try creating a new thread where you explain your goals, what you do now, and why it doesn't work.
 
Back
Top