Filewatcher - checking for file completed using this example

I have a file watcher code that actually someone here (Eric - emaru?) helped me with. I need to make a change to the code and not sure how to do it.

I have this example:
http://stackoverflow.com/questions/4277991/c-sharp-filesystemwatcher-how-to-know-file-copied-completely-into-the-watch-fol

If you scroll down, i want to do this;
I subscribe to the Changed- and Renamed-event and try to rename the file on every Changed-event catching the IOExceptions. If the rename succeeds, the copy has finished and the Rename-event is fired only once.

Based on this http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx
I need:
1. watcher.Renamed += new RenamedEventHandler(OnRenamed);
2. what do I need in OnRenamed?3. watcher.Changed += new FileSystemEventHandler(OnChanged);
4. what do I need in OnChanged here?


LVL 8
CamilliaAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

pivarCommented:
Hi,

I've used the following method to check if the fileevent is completed for FileSystemWatcher events Created and Changed

public static bool IsFileClosed(string filename) {
	try {
		FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
		fs.Close();
		fs.Dispose();
	} catch (IOException) {
		return false;
	} catch {
	}

	return true;
}

Open in new window


/peter
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
CamilliaAuthor Commented:
Peter, I should put this in onCreated event?
0
pivarCommented:
You could. I usually add the filename to a list in the event and have another thread looping through the list checking completeness and if so handling the file. But it depends on the amount of files and work per each file.
0
Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

pivarCommented:
You could. I usually add the filename to a list in the event and have another thread looping through the list checking completeness and if so handling the file. But it depends on the amount of files and work per each file.
0
pivarCommented:
oops, I managed to doublepost.
0
CamilliaAuthor Commented:
trying this now. Might need help with thread looping you mention. The files get copied to the server maybe twice a day. Not a constant file copying. Let me try this and will post back.
0
pivarCommented:
Well In that case you might not need the threading. I'm thinking of situations where you have a lot more constantly incoming files.
0
CamilliaAuthor Commented:
Ok, your code works but now I dont know how I can recheck the file-completion copy and do whatever I need to do with it.

This is my process:
1. I copy a file from one server to another, server2
2. When file is on server2, I call a stored proc to import the file. That's it.
---- This is what I have now
1. I copy a file from one server to another, server2
2. Check if file is copied on server2 in onChanged event
3. Now, how do I get back to checking if it's completed and import it??

This is my code.  I have your code in step 4




//when file is first copied to NAS server
 if (server == "NAS")
            {
                watcher.Created += new FileSystemEventHandler(OnChangedGP);
               (OnRenamedGP);
            }
            else
                watcher.Created += new FileSystemEventHandler(OnChanged);

//2. Move the file from NAS to the other server on onChanged event
private void OnChangedGP(object source, FileSystemEventArgs e)
        {


		string fileName = e.Name;


              try
            {
                switch (fileName)
                {
                    
                    case "NXB.txt":
                        MoveFile(fileName, "NAS");
                        break;

                    default:

                        break;
                }

            }
            catch (Exception)
            {


            }
             
      }

//3. Moves the file to second server
private void MoveFile(string filename, string flag)
        {
            //move file to server2 here
        }

//4. File is on server 2. Checks to see if file copy is complete. I got a "false" but then it never got back here to actually import it

private void OnChanged(object source, FileSystemEventArgs e)
        {
            // Specify what is done when a file is changed, created, or deleted.
            string fileName = e.Name;
            try
            {
                switch (fileName)
                {
                    ....
                    case "NXB.txt":

                        bool fileCopyComplete = IsFileClosed(fileName);
                        if (fileCopyComplete) // i get false here but that's it. Then file is on server2..when would I get to import it then??
                        {
                            ImportFile("NXB", 0);
                            MoveFile(fileName, "GP");
                        }
                        break;
                    default:

                        break;
                }

            }
            catch (Exception ex)
            {
                Log(e.Name, ex.Message);

            }

        }

Open in new window

0
pivarCommented:
If IsFileClosed is false, then the file isn't completed. Then you have to wait until the file is completed. You could try next file in list, without removing the uncompleted file. So you'll try that file on next loop again or you could use a method like

public static bool IsFileClosed(string filename, int retries, int sleepms) {
	bool result = false;

	while (retries-- > 0) {
		if (IsFileClosed(filename)) {
			result = true;
			break;
		}
		System.Threading.Thread.Sleep(sleepms);
	}
	return result;
}

Open in new window


to wait for the file to complete.
0
CamilliaAuthor Commented:
yes, found this example. The site is a bit slow to load. I think this should work. Similar to yours
http://bloggingabout.net/blogs/jschreuder/archive/2006/07/06/12886.aspx
0
pivarCommented:
Is it working now or do you need some more advice?
0
CamilliaAuthor Commented:
I tested it yesterday and it seems like it's working. Going to close this question now. Thanks for your help.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.