I'm using code that relies on methods of the FileSystemObject object. As Listing 2 shows, the code first uses the FileExists method to determine whether a certain text file exists. If the file doesn't exist, the code uses the CreateTextFile method to create the text file. However, when the code attempts to use the OpenTextFile method to open the text file, the script generates an error stating that I don't have Write permissions to the file. If I run the script again, the script shows that the file already exists, then opens and writes to the file, without any problem. What's going on?
The problem is that the CreateTextFile method still has a handle to the newly created file. One solution is to add the Close method after creating the text file. You can do so by adding objFile.Close immediately before the End If statement.
A more elegant solution would be to rely solely on the OpenTextFile method, altogether avoiding the FileExists and CreateTextFile methods. The OpenTextFile method's third parameter, Create, is a Boolean value that specifies whether the file should be created if it doesn't already exist. By setting this value to True (as the code at callout A in Listing 3 does) when calling the OpenTextFile method, you tell the method to create the file if it doesn't exist, then open the file. Note that the OpenTextFile method's ForWriting parameter specifies that a new file will be created. When you're attempting to append to a file (e.g., an ongoing log file), use the method's ForAppending parameter instead.