1

In my VB.net application I am opening a PDF file using

System.Diagnostics.Process.Start("c:\TEMP\MyFile.pdf").

I would like to safely delete this file in some event if it is not open.

dsolimano
  • 8,870
  • 3
  • 48
  • 63
sanika
  • 79
  • 1
  • 3
  • 14
  • 4
    To detect if it's open, try to open it. It will throw an exception if it is already open. See http://stackoverflow.com/a/11288781 – Robert Harvey Apr 17 '13 at 15:16

2 Answers2

3

Simply attempt to delete the file:

System.IO.File.Delete("THEFILE")

If the file is open, this line of code will throw an exception. You can (and should) handle that case by wrapping it with a Try and Catch block. For example:

Try
    ' Attempt to delete the file. This will succeed unless the file is in use.
    System.IO.File.Delete("THEFILE")
Catch ex As IOException
    ' The file was in use, so it cannot be deleted.
    ' Do something here...or nothing if you just want to ignore such a case.
End Try
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
06needhamt
  • 1,555
  • 2
  • 19
  • 38
  • Yes, that is how I am trying to delete it but I don't want it to throw an exception. If the file is open then I want it to be closed and then deleted. – sanika Apr 17 '13 at 19:00
  • @sanika: Add `Try... Catch` block around this statement? – Victor Zakharov Apr 17 '13 at 19:38
  • Yes I do have try catch block. But I don't like the logic of catching an error and not handling it – sanika Apr 18 '13 at 13:45
  • 1
    @sanika That's a good general guideline, but it's actually your only viable option in this case, because you're dealing with the file system. Any way of checking if the file is deletable *first* before attempting to delete it is subject to a race condition. You would *still* have to use try/catch to handle errors. So you might as well just do that from the start. Same discussion [here](http://stackoverflow.com/questions/15362518/checking-if-a-file-is-in-use-without-try-catch/). – Cody Gray - on strike Apr 19 '13 at 02:10
0

Your question is asking for help deleting a file if it isn't open. You seem to not like the responses given even though they are doing that.

Do you want to delete the file ONLY if it isn't being used? In that case you do what has been mentioned, you use Try... Catch. If it throws an exception, then it is in use - and YOU DON'T WANT TO DELETE IT, otherwise you delete it.

However the responses you have given make it seem like you want to delete it regardless. Remember that after you load it into vb, is is classified as being used, and you will need to dispose of it when you claim to have finished using it. It will not be disposed every time it is idle. If you want to use it, dispose of it, either using the .Dispose method, or by setting whatever is holding it to Nothing.

Michael Parr
  • 134
  • 3
  • 14