Visual Basic: Checking if file exists, if not, cre

2019-09-19 09:33发布

问题:

This is the code. It checks if the file in path exists, if not, it creates the file. I'm getting this error message all the time and I don't know why. Maybe I should close the System.IO.Directory.Exists? If yes, how do I do that? Just so you know, I'm creating a text file.

The code

If Not (System.IO.Directory.Exists(path)) Then
        Dim fs3 As FileStream = File.Create(path)
    End If

This is the error message I get:

Process can't use the file (path) because some other process is using this file at the moment.

回答1:

The file is used by other processes hence it can't be overwritten. I suggest you delete the file first.

Dim path As String = "put your path"

For Each path In System.IO.Directory.GetFiles("C:\WINDOWS\TEMP")
System.IO.File.Delete(path)
Next path

Dim fs3 As FileStream = File.Create(path)

Be certain that you have full rights [under properties] to the folder.