I am using a third-party library to convert a document into a PDF. The output file name will be arbitrary -- provided by the client. If a file with that name already exists, my code will modify the file name in a fashion similar to the way MS Windows does, e.g. "myname.txt" becomes "myname (1).txt". I would like to reserve the output file name somehow so that my code is not only thread-safe but also "process safe", meaning that another application's process won't create the file after my code has determined the unique file name it wants to use but before it actually creates the file.
The usual or simple approach, it would seem, is to make use of exception handling and a loop structure when writing the file to create a unique file name when the previous write attempt failed because a file with that name already exists. However, since the third-party implementation for writing the file undoubtedly has side effects which I don't want to incur multiple times in my loop, I would like to find a way to guarantee that the file name will be available the first time I call the third-party code to write the file.
Is there a way to do this?