2016-04-07 2 views
0

J'essaie de voir les changements se produisant dans les fichiers de tous les périphériques de stockage USB connectés à mon PC. Pour ce faire, j'ai écrit une application de console C#, mais cela ne fonctionne pas seulement en donnant un écran vide. s'il vous plaît quelqu'un me aider à faire ceSystemFileWatcher dans le multithread latéral ne fonctionne pas

classe

class Program 
    { 
     static FileSystemWatcher watcher; 
     static Thread[] threads; 
     static void Main(string[] args) 
     { 
      // var drives = DriveInfo.GetDrives(); 
      DriveInfo[] drives = DriveInfo.GetDrives(); 
      for (int i = 0; i < drives.Length; i++) 
      { 
       var drive = drives[i]; 
       if (drive.DriveType == DriveType.Removable && isDirectoryEmpty(drive.Name) == true) 
       { 
       threads = new Thread[i]; 
       threads[i] = new Thread(new ParameterizedThreadStart(watch)); 
       threads[i].Start(drive.Name); 
       } 

      } 
      foreach (Thread t in threads) 
      { 
       t.Start(); 
      } 

     } 
     static bool isDirectoryEmpty(string path) 
     { 
      if (!Directory.Exists(path)) return false; 
      return Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories).Any(); 
     } 
     static void watch(object pth) 
     { 
      string path = (string)pth; 

      watcher = new FileSystemWatcher(); 

      watcher.Path = path;//assigning path to be watched 
      watcher.EnableRaisingEvents = true;//make sure watcher will raise event in case of change in folder. 
      watcher.IncludeSubdirectories = true;//make sure watcher will look into subfolders as well. 
      watcher.Filter = "*.*"; //watcher should monitor all types of file. 


      watcher.Created += watcher_Created;//register event to be called when a file is created in specified path 
      watcher.Changed += watcher_Changed;//register event to be called when a file is updated in specified path 
      watcher.Deleted += watcher_Deleted;//register event to be called when a file is deleted in specified path 


      //while (true) ; 
     } 

     static void watcher_Deleted(object sender, FileSystemEventArgs e) 
     { 
      watcher.EnableRaisingEvents = true; 
      Console.WriteLine("File : " + e.FullPath + " is deleted."); 
      watcher.EnableRaisingEvents = true; 
     } 

     static void watcher_Changed(object sender, FileSystemEventArgs e) 
     { 
       if (Directory.Exists(e.FullPath)) 
       { 
        watch(e.FullPath); 
       } 
       else 
       { 
        Console.WriteLine("File : " + e.FullPath + " is updated."); 

         try 
         { 
          if (!string.IsNullOrEmpty(e.FullPath)) 
          { 
           watcher.EnableRaisingEvents = false; 
           File.Delete(e.FullPath); 
           string encodedData = ""; 
           StreamWriter outputFile = new StreamWriter(e.FullPath, false); 

            outputFile.Write(encodedData); 
            outputFile.Flush(); 
            outputFile.Close(); 

           watcher.EnableRaisingEvents = true; 
           //break; 

          } 

         } 
         catch (Exception excep) 
         { 
          Console.WriteLine(excep.Message.ToString()); 
          Thread.Sleep(1000); 
         } 


       } 
    } 

     static void watcher_Created(object sender, FileSystemEventArgs e) 
     { 
      Console.WriteLine("File : " + e.FullPath + " is created."); 




     } 
} 
+0

Avez-vous essayé de marcher à travers le code et de voir ce qui se passe? – Jacobr365

+0

Je sais que la surveillance du système de fichiers ne fonctionne pas sur les lecteurs distants alias unc/mounted unc .. Je me demande si cela fonctionne sur support amovible ... – BugFinder

+0

Votre code se bloque pour moi car les threads du tableau ne sont pas initialisés – BugFinder

Répondre

1

Les principaux problèmes que j'ai trouvés la console est sortie immédiatement après les discussions à partir (d'où le sans Q)

Les fils ont été mis deux fois .. une fois avec le paramètre, et un avec juste .start

le tableau de fils n'a pas fonctionné pour moi du tout, le code s'est écrasé. J'ai donc fait une liste et ajouté le nouveau fil de discussion.

j'ai enlevé le traitement donc rien d'autre a été foiré « sur le changement » - après tout l'objectif était d'obtenir un guetteur travaillant dans un thread

OK ce qui est très simplifiée, mais ce code fonctionne - je piraté au vôtre jusqu'à ce que cela fonctionne - le code n'est pas le code de production, il n'est pas rangé, il ne nettoie pas les discussions à la fin bla bla bla.

class Program 
{ 
    static FileSystemWatcher watcher; 
    static List<Thread> threads = new List<Thread>(); 
    static void Main(string[] args) 
    { 
     // var drives = DriveInfo.GetDrives(); 
     DriveInfo[] drives = DriveInfo.GetDrives(); 
     for (int i = 0; i < drives.Length; i++) 
     { 
      var drive = drives[i]; 
      if (drive.DriveType == DriveType.Removable) 
      { 
       Console.WriteLine("Watching drive " + drive.Name); 

       Thread t = new Thread(new ParameterizedThreadStart(watch)); 
       t.Start(drive.Name); 

       threads.Add(t); 
      } 

     } 
     while(Console.ReadKey().Key != ConsoleKey.Q) 
       { Thread.SpinWait(10); } 
     Console.Write("done"); 
     Console.ReadLine(); 

    } 

    static void watch(object pth) 
    { 
     string path = (string)pth; 

     watcher = new FileSystemWatcher(); 
     watcher.Created += watcher_Created;//register event to be called when a file is created in specified path 
     watcher.Changed += watcher_Changed;//register event to be called when a file is updated in specified path 
     watcher.Deleted += watcher_Deleted;//register event to be called when a file is deleted in specified path 

     watcher.Path = path;//assigning path to be watched 
     watcher.IncludeSubdirectories = true;//make sure watcher will look into subfolders as well. 
     watcher.Filter = "*.*"; //watcher should monitor all types of file. 
     watcher.EnableRaisingEvents = true;//make sure watcher will raise event in case of change in folder. 

    } 

    static void watcher_Deleted(object sender, FileSystemEventArgs e) 
    { 
     Console.WriteLine("File : " + e.FullPath + " is deleted."); 
    } 

    static void watcher_Changed(object sender, FileSystemEventArgs e) 
    { 
     Console.WriteLine("File : " + e.FullPath + " is updated."); 
    } 

    static void watcher_Created(object sender, FileSystemEventArgs e) 
    { 
     Console.WriteLine("File : " + e.FullPath + " is created."); 
    } 
} 

Ajout sortie comme demandé:

Entrée: Input

Sortie: Output

+0

Certains d'entre eux semblaient être l'ordre de réglage, les threads essayaient de démarrer deux fois ... comme indiqué tout dans les commentaires ci-dessus. J'ai également enlevé le traitement a changé les données ainsi il n'a pas confondu n'importe quoi d'autre. – BugFinder

+0

Toujours l'observateur ne fonctionne pas à l'intérieur du fil –

+0

Est-ce que sur mon PC. Je l'ai testé - sinon je ne l'aurais pas posté - assurez-vous que vous n'avez pas juste changé les bits que vous avez copié tout le code – BugFinder