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.
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.
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
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
.