Click here to Skip to main content
15,890,670 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have 2 systems need to handle below scenario

01.System one is writing text into file at shared location. we are not aware about that system how its writing.

02. We need to write c# program should copy only completed file from shared location.

now problem is how should i check the file is complete or not . system one might be writing data into file which i am coping?

What I have tried:

c# program is not able to detect if file is open in notepad or notepad++
Posted
Updated 8-Feb-22 21:44pm
v2
Comments
Maciej Los 21-Jun-18 9:56am    
You have to define what you mean by saying "check if file is complete"...
Eric Lynch 21-Jun-18 17:07pm    
Don't know if this would work for you...for similar requirements, in the past, I've initially written to a temporary directory or file name. Then, I've renamed/moved the file only AFTER its complete. That way the process that reads the file only ever sees completed files.

First of all, please read my comment to the question...

If there's no process which locks file during read/write operation, there's no chance to find out if specific file is "completed" or no. But...

There's a FileSystemWatcher Class (System.IO)[^], which is listening for file system change notifications and raises events when a directory, or file in a directory, changes. See the list of: FileSystemWatcher Events (System.IO)[^]

Good luck!
 
Share this answer
 
Comments
ahp-1984 21-Jun-18 10:07am    
thanks Maciej
Maciej Los 21-Jun-18 10:26am    
You're very welcome
Dave Kreskowiak 21-Jun-18 11:57am    
But FileSystemWatcher in no way tells you that the file is "complete". It only tells you that the file has changed in some way.

You still have to TRY to open the file and read it's contents. If the open operation fails, the file is still being written. You're going to have to wait an arbitrary amount of time and try again.
FileSystemInfo.LastWriteTime Property (System.IO) | Microsoft Docs[^]

I use FileSystemInfo.LastWriteTime compare with Datetime.Now to find that file has stopped writing.
If file hasn't been write in 10 seconds, I assunme it's complete.
 
Share this answer
 
Comments
Richard Deeming 9-Feb-22 4:39am    
Be aware that the property you're using returns the local time. If DST starts or ends whilst you're checking, your code will probably break. Either it will be stuck waiting for an hour until the local clock catches up, or it will assume a file that was last modified 1 second ago was actually last modified over an hour ago.

If you're going to do something like this, always use UTC - compare the LastWriteTimeUtc[^] property to DateTime.UtcNow.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900