I am writing a program to copy files from one location to another. I only want to copy the files that is not in writing mode. Here is the logic:

(1) If the file is not opened (by any application), copy it;
(2) If the file is opened (by any application) but not in writing mode, copy it;
(3) If the file is opened and is in saving/writing mode, don't copy it.

I put FileInfo.Open method in a TRY block and try to catch an exception to determine if the file is in Writing mode. But it does not work -- I am going to get an exception for both (2) and (3). In other word, I can not get info if a file is in writing mode.

Thank you in advance for giving me a help.

Recommended Answers

All 4 Replies

Can you post a code block?

Here is the code. I have played different parameters for OPEN method. It seems this is not a right approach.

Private Function IsFileWriting(ByVal strFileName As String) As Boolean

Dim fiFile As FileInfo
Dim fsStream As FileStream

fiFile = New FileInfo(strFileName)
fsStream = fiFile.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)
LogWriter.WriteLog("The file is NOT in writing mode. Ready to copy file: " + strFileName)

Catch exIO As IOException
LogWriter.WriteLog("The file is in writing mode. Can NOT copy file [" + strFileName + "].")
Return True

Catch exAccess As UnauthorizedAccessException
LogWriter.WriteLog("File is in Use! " + exAccess.ToString, "FileProcessor.IsFileWriting")
Return False

Catch ex As Exception
LogWriter.WriteError("Unexpected error! " + ex.ToString, "FileProcessor.IsFileWriting")

fiFile = Nothing

End Try

Return False
End Function

I assume, that that FiFile.Open() is throwing your exception. If that is the case, your not trapping the proper exceptions. Consult the MSDN Documentation for the exceptions that FileInfo.Open() throws.

Also, I don't think you're going to be able to tell the difference between if the file is already open and the file is opened for writing. You will probably need to write some Win32 code here to get the information you need.

Once the file is opened, I always get an UnauthorizedAccessException. You are right -- cannot distinguish opened and in writing. Any clue what to do using Wind32?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.