0

So I am having a synchronization program and I am using the filesystemwatcher to watch the changing in a directory. Now I had a listbox and I would add a different text at Changed, Created, Renamed and Deleted. Now what I noticed was, sometimes when I create a file it gives me the text:

"File has been created"

"File has been changed"

I read somewhere that the filesystemwatcher shouldn't be used cause the events are triggered when sometimes it shouldn't be.

Now I get this problem(I think it's because of the multiple events at once), When I drag a file in the directory I am watching, It should copy the file to the 2nd directory. If it already exists in the 2nd directory it should delete it and then copy it. Now I got the error:

The process cannot access the file because it is being used by another process

At the line where I delete the existing file in the 2nd directory. Now I was wondering wether the Filesystemwatcher is the problem here. Since it also triggers events and maybe it is still being "changed". which shouldn't have been triggered.

My question is:

Is the filesystemwatcher the problem?(So more like, is this a known problem?)

If so:

Is there something to replace the filewatcher with?

If not, this is my code + explanations of some variables:

Source = the first directory

target= the second directory

Record(); = executes readquery

postgresql(); = inserts in postgressql with the strSelectCmd (Has nothing to do with it)

        public static void copyfolder()
    {
        String source = ConfigurationManager.AppSettings[@"Directory1"];
        String target = ConfigurationManager.AppSettings[@"Directory2"];

        Copy(@source, @target);
    }

(string.IsNullOrEmpty(filename) == false) The actuall check if the file exists in the database.

 private void fileSystemWatcher1_Created(object sender, System.IO.FileSystemEventArgs e)
        {
            if (!pause)
            {
                logger("File created> " + e.FullPath + " -Date:" + DateTime.Now);
                filepath = Path.Combine(source, e.Name);
                name = Path.GetFileNameWithoutExtension(filepath);
                extension = Path.GetExtension(e.FullPath);
                size = e.Name.Length;
                strSelectCmd = "INSERT INTO" + tablepostgresql + " (" + column1 + "," + column2 + "," + column3 + "," + column4 + ") VALUES('" + name + "','" + size + "',now(),'" + extension + "')";
                readquery = "select * from " + tablemysql + " where name='" + name + "'";
                postgresql();
                Record();

                if (string.IsNullOrEmpty(filename) == false)
                {

                    if (Directory.Exists(e.FullPath))
                    {
                        copyfolder();
                        Directory.CreateDirectory(target);
                    }
                    else
                    {
                        if (WaitForFileAvailable(e.FullPath, TimeSpan.FromSeconds(30)))
                        {
                            var file = Path.Combine(source, e.Name);
                            var copy_file = Path.Combine(target, e.Name);
                            var destination = Path.Combine(target, Path.ChangeExtension(source, Path.GetExtension(source)));
                            if (File.Exists(copy_file))// Check to see if the file exists. 
                            {                     //If it does delete the file in the target and copy the one from the source to the target.
                                File.Delete(copy_file);
                            }
                            File.Copy(e.FullPath, copy_file);

                        }
                        else // The file failed to become available within 10 seconds.
                        {
                            logger("Copy has failed reason: File is being used by another program");
                        }

                    }
                }
                    if (demo == "yes")
                    {
                        query = "INSERT INTO " + tablemysql + " (name,size,last_edit,extension) VALUES('" + name + "','" + size + "',now(),'" + extension + "')";
                        Mysql();
                    }

            }
        }

The error appears at this line:

File.Delete(copy_file);
Loko
  • 6,539
  • 14
  • 50
  • 78
  • 1
    Most likely, the problem is in your code; please, post it such that we can help you. – varocarbas Nov 28 '13 at 10:47
  • @varocarbas The problem is, I have alot of app config variables. So you wouldn't understand it. I can do it in chat? – Loko Nov 28 '13 at 10:49
  • 1
    Read also this http://stackoverflow.com/questions/1764809/filesystemwatcher-changed-event-is-raised-twice and this http://stackoverflow.com/questions/699538/file-access-error-with-filesystemwatcher-when-multiple-files-are-added-to-a-dire – Jehof Nov 28 '13 at 10:50
  • The whole point of SO is not delivering a custom solution for your problems; but solving a problem which might be useful for others. Chat might be useful under very specific conditions; but you should be able to describe the exact problem (the relevant parts of your code) here. Then we can chat to clarify some details if required. – varocarbas Nov 28 '13 at 10:51
  • @varocarbas yes I get it but if it is my code that is the problem then I dont think it would be usefull for others since there would probably be a problem with the placement of some functions. – Loko Nov 28 '13 at 10:53
  • The problem you refer is provoked because of intending to access a file which is being accessed from somewhere else; by assuming that this second access is executed from your application (otherwise we wouldn't be able to help you), the relevant parts are the ones accessing this file (e.g., how this file is accessed, how the variables are disposed, how are declared all the involved variables, etc.). The exact inputs are not relevant, but the file-access structure which you should be able to post here without any problem. If we cannot understand any part, would ask you for clarifications. – varocarbas Nov 28 '13 at 10:56
  • @varocarbas I'll do my best and I'll try to turn my code around a little so you get it. – Loko Nov 28 '13 at 10:57
  • Actually the second link proposed by Jehof might be pretty handy. Perhaps you should take a look at it in detail and confirm that it does not solve your problem before going ahead and posting your code here. – varocarbas Nov 28 '13 at 11:00
  • OK. Can you please explain when happens this error exactly and in which line? Also can you add the code for copyfolder()? – varocarbas Nov 28 '13 at 11:14
  • Thanks (although now the question is: what is `Copy(@source, @target);` :)) still there is not enough information. Where is `target` coming from? what is its relationship with `e.FullPath`? So many variables are confusing and have provoked that your algorithm is intending to delete a file it is dealing with. The way to fix this (other than the evident option: always put a try..catch while doing things in the file system like deleting, moving, etc.) is knowing why is this happening: where is the file you are intending to delete being used? Make all the variables known to us or debug it. – varocarbas Nov 28 '13 at 11:26
  • @varocarbas I already explained what the source and target are in the question. e.FullPath is the path of the file that triggered the event. Well thanks anyway. I'll try it with try and catch. – Loko Nov 28 '13 at 11:29
  • (I didn't mean that but well...) Yes the try...catch will undoubtedly solve it if with solving you mean not triggering the error; but the file will not be deleted. You are getting this error because of intending to access a file which is opened with write permissions; you don't do that while copying or using its name (to connect to the DB, for example). You might do that by creating the file and not disposing the objects properly; by opening the file and not closing it, etc. You are doing something like that in some part of your code, not in what you have shown. – varocarbas Nov 28 '13 at 11:32

0 Answers0