-2

I want to test if a file is in use. The code as follows was provided and it works! The problem now is that if I want to open the text file via notepad my vb.net app which just checked if the file is in use holds retains possession over it. How do I test if the file is in use but not take possession of it either. Releasing the file immediately after testing if its in use also works for me. Ive also tried to insert FileClose(1) but to no avail?

        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Try
            System.IO.File.Open("C:\test.txt", IO.FileMode.Open,
            IO.FileAccess.Read, IO.FileShare.None)
            MsgBox("In Use")
        Catch ex As Exception
            MsgBox("Not in use")
        End Try
    End Sub
End Class
LabRat
  • 1,996
  • 11
  • 56
  • 91
  • Possible duplicate of [Closing a file after File.Create](https://stackoverflow.com/questions/5156254/closing-a-file-after-file-create) – esqew Jun 04 '19 at 19:57
  • Fail to see how thats a duplicate as the link shows a file being created. Im not creating but trying to check somthing that has already been created – LabRat Jun 04 '19 at 20:01
  • @ABANDONDACOUNT Have you tried wrapping the `File.Open` call in a `Using` block? – JayV Jun 04 '19 at 20:11
  • Since this isn't my occupation and I have to reverse engineer it says very little to me. Im assuming that the example with file.stream was the way to go then however that for some reason failed to even produce a correct result let alone close the file for me – LabRat Jun 04 '19 at 20:20

1 Answers1

0

File.Open() opens a FileStream. If you don't close it, the next attempt to open the same stream will result in an IOException. Put it in a Using block, as suggested by JayV, and it should work fine:

    Try
        Using System.IO.File.Open("C:\test.txt", IO.FileMode.Open,
              IO.FileAccess.Read, IO.FileShare.None)
            MsgBox("In Use")
        End Using
        MsgBox("Disposed, not in use")
    Catch ex As Exception
        MsgBox(ex.StackTrace)
    End Try

This will open the FileStream, confirming that it isn't being used by someone else, and then close it, even if an Exception is thrown. If you were to use an explicit disposal (i.e., FileStream.Close()), you'd have to add a Finally block to your Try/Catch and close it there.

  • I have no idea where to place this in the code i'm completely unfamiliar with the Using block – LabRat Jun 04 '19 at 20:43
  • It's pretty much the same thing that you shared, but with the added Using. I'll edit in a minute. – Mariano Luis Villa Jun 04 '19 at 20:45
  • @MarianoLuisVilla I think that the `MsgBox("In Use")` needs to be inside the `Using` block. As your code stands when the `MsgBox` is shown the file lock will be released. – JayV Jun 04 '19 at 21:13
  • @MarianoLuisVilla I tried youe edit but it just keeps on saying file in use even if ive closed it? I will restart my computer hoping it might just be a stuck in memmory issue – LabRat Jun 04 '19 at 21:18
  • nor any change in results after a restart and emptying of my %Temp% folder (Where crap often seems to accumulate and cause memory contamination) – LabRat Jun 04 '19 at 21:26
  • @ABANDONDACOUNT Move the line `MsgBox("In Use")` to before the line `End Using`. While the message is displayed, the file will be locked. When you dismiss the message, the file will be unlocked. – JayV Jun 04 '19 at 21:31
  • ` Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim teststring As String = "" Try Using System.IO.File.Open("C:\test.txt", IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.None) End Using teststring = "InUse" Catch ex As Exception teststring = "NotInUse" End Try If teststring = "InUse" Then MsgBox("In use") ElseIf teststring = "NotInUse" Then MsgBox("Not In use") End If End Sub` – LabRat Jun 04 '19 at 21:58
  • I get what your saying but I tested it with the above code and it still always prompts file in use – LabRat Jun 04 '19 at 22:00
  • @JayV You're totally right, I honestly payed no mind to the `MsgBox` and was just trying to make sure the resource was being disposed. @ABANDONDACOUNT, I think you're being missled by the messages. I've just edited the answer. I tested the above code a minute ago, and even re-opened the same file rigth after the `End Using` statement; try that and you'll find the file is available for usage. – Mariano Luis Villa Jun 04 '19 at 23:07
  • I only had a short time to test the edited code before going to work. @JayV I think your right and the messages are causing confusion. Regardless the message is still always the same. Of cause what my intension is, is not to close a file which is open but to only check it. What I think this answer has provided me with is a code that checks if the process is being used, then closes it if it is being used and that the message boxs actually have no informative value as they now will undoubtedly always say not in use because I ether way the file is already closed is has been close by your code? – LabRat Jun 05 '19 at 05:31
  • @ABANDONDACOUNT The code checks if a file exists by trying to open it's pressumed path. If the file doesn't exist, you'll get an `Exception`. The extra bits are to make sure that, if the file exists (and therefore has been opened), it'll get closed, so you can actually do something with it if you need to. – Mariano Luis Villa Jun 05 '19 at 13:54
  • Well I will have to accept that the code works (which i also truely belive) but in all honesty it dosnt do anything on my system and i have no clue why because it cant get more basic than being a cut and paste code... – LabRat Jun 05 '19 at 15:47