Skip to content
TheChatArchiveThe Chat Archive
gpt-4-1106-preview· openaiHugging Face Suzhen/CodeChat

using System; using System.IO; using System.Threading; namespace…

  1. User

    using System; using System.IO; using System.Threading;

    namespace Ekiscopp.Modele.Generateur_appli.data { public delegate void DelegateFunction(string message);

    public class FileModificationListener
    {
    	private string path;
    	private FileSystemWatcher _watcher;
    	private DelegateFunction myDelegateFunction;
    
    	public FileModificationListener(DelegateFunction myDelegateFunction)
    	{
    		this.myDelegateFunction = myDelegateFunction;
    	}
    
    	public void SetPath(string path)
    	{
    		StopWatching();
    		this.path = path;
    		StartWatching();
    	}
    
    	public void StopWatching()
    	{
    		if (_watcher != null)
    		{
    			_watcher.EnableRaisingEvents = false;
    			_watcher.Dispose();
    		}
    	}
    
    	private void StartWatching()
    	{
    		string directory = Path.GetDirectoryName(path);
    		if (!Directory.Exists(directory))
    		{
    			Console.WriteLine("Invalid directory path.");
    			return;
    		}
    
    		string filename = Path.GetFileName(path);
    
    		Console.WriteLine(filename);
    
    		_watcher = new FileSystemWatcher(directory)
    		{
    			NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName,
    		};
    
    		// Subscribe to the events of the FileSystemWatcher
    		_watcher.Changed += OnChanged;
    		_watcher.Created += OnChanged;
    		_watcher.Deleted += OnChanged;
    		_watcher.Renamed += OnRenamed;
    		_watcher.Error += OnError;
    
    		_watcher.EnableRaisingEvents = true;
    	}
    
    	private void OnChanged(object sender, FileSystemEventArgs e)
    	{
    		Console.WriteLine($"FullPath: {e.FullPath}, Name: {e.Name}, Expected Path: {path}");
    
    		if (e.Name != Path.GetFileName(path))
    		{
    			return;
    		}
    		if (e.ChangeType == WatcherChangeTypes.Changed)
    		{
    			DateTime lastModified = File.GetLastWriteTime(e.FullPath);
    
    			// Display last modification time in the format hh:mm:ss
    			string message = "Dernière modification : " + lastModified.ToString("HH:mm:ss");
    			Console.WriteLine(message);
    
    			// Invoke the delegate on the UI thread if necessary
    			myDelegateFunction(message);
    		}
    	}
    
    	private void OnRenamed(object sender, RenamedEventArgs e)
    	{
    		// Add logic for file renaming if needed
    	}
    
    	private void OnError(object sender, ErrorEventArgs e)
    	{
    		// Handle error events if needed
    		Console.WriteLine("Error: " + e.GetException().Message);
    	}
    }
    

    }

    voilà ce que ça print quand je modifie dans l'ordre: un fichier excel (celui sur expected path) un autre et que je fais des tests en créant/modifiant un fichier .txt

    FullPath: D:\rangement\1227F200, Name: 1227F200, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx FullPath: D:\rangement\1227F200, Name: 1227F200, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx FullPath: D:\rangement\1227F200, Name: 1227F200, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx FullPath: D:\rangement\6351768C.tmp, Name: 6351768C.tmp, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx Le thread 0x317c s'est arrêté avec le code 0 (0x0). FullPath: D:\rangement~parametrage.xlsx,Name: parametrage.xlsx, Name: ~parametrage.xlsx, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx FullPath: D:\rangement~parametrage.xlsx,Name: parametrage.xlsx, Name: ~parametrage.xlsx, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx FullPath: D:\rangement\5148F200, Name: 5148F200, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx FullPath: D:\rangement\5148F200, Name: 5148F200, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx FullPath: D:\rangement\5148F200, Name: 5148F200, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx FullPath: D:\rangement\140ACD1D.tmp, Name: 140ACD1D.tmp, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx FullPath: D:\rangement\2C48F200, Name: 2C48F200, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx FullPath: D:\rangement\2C48F200, Name: 2C48F200, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx FullPath: D:\rangement\2C48F200, Name: 2C48F200, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx FullPath: D:\rangement\5A1AF87A.tmp, Name: 5A1AF87A.tmp, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx Le thread 0x5600 s'est arrêté avec le code 0 (0x0). FullPath: D:\rangement\Nouveau document texte.txt, Name: Nouveau document texte.txt, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx FullPath: D:\rangement\test.txt, Name: test.txt, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx

    le problème c'est que je veux filtrer sur la modification d'un fichier excel en particulier (expected path)

  2. Assistant

    Il semble que le programme est configuré pour détecter des modifications sur tous les fichiers du répertoire spécifié, pas uniquement sur un fichier Excel spécifique. La méthode OnChanged vérifie si le nom de fichier modifié est celui attendu avant de traiter l'événement, mais le FileSystemWatcher ne fait pas de distinction, il déclenche des événements pour toute modification sur n'importe quel fichier dans le répertoire surveillé.

    Excel est assez déroutant parce qu'il ne modifie pas directement le fichier original lorsque vous y apportez des changements. Au lieu de cela, il crée plusieurs fichiers temporaires et d'autres fichiers de sauvegarde (comme ceux commençant par ~$ ou avec des extensions .tmp). Ces fichiers sont créés et supprimés fréquemment dans le processus normal de travail avec Excel. C'est pourquoi vous voyez ces événements apparaitre.

    Pour filtrer les modifications et ne réagir qu'aux changements sur le fichier Excel spécifique que vous souhaitez suivre, vous pouvez ajuster votre méthode OnChanged pour qu'elle vérifie explicitement si le fichier modifié est celui qui vous intéresse, comme c'est partiellement le cas avec la condition if (e.Name != Path.GetFileName(path)).

    Cependant, vous devriez également prendre en compte que certains des événements de modification peuvent être causés par ces fichiers temporaires qu'Excel utilise. Pour cela, vous pouvez vérifier l'extension du fichier modifié et faire en sorte de ne pas réagir aux fichiers temporaires. Voici un exemple de code ajusté pour la méthode OnChanged qui illustre ceci :

    private void OnChanged(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine($"FullPath: {e.FullPath}, Name: {e.Name}, Expected Path: {path}");
    
        string eventFileName = Path.GetFileName(e.FullPath);
        string expectedFileName = Path.GetFileName(path);
    
        // Check if the event is related to the expected file
        if (string.Equals(eventFileName, expectedFileName))
        {
            if (e.ChangeType == WatcherChangeTypes.Changed)
            {
                DateTime lastModified = File.GetLastWriteTime(e.FullPath);
    
                // Display last modification time in the format hh:mm:ss
                string message = "Dernière modification : " + lastModified.ToString("HH:mm:ss");
                Console.WriteLine(message);
    
                // Invoke the delegate
                myDelegateFunction(message);
            }
        }
        else
        {
            // Here we can decide to ignore temporary files.
            // For example, don't invoke the delegate for temp files or files starting with '~$'.
            if (eventFileName.EndsWith(".tmp", StringComparison.OrdinalIgnoreCase) ||
                eventFileName.StartsWith("~$", StringComparison.OrdinalIgnoreCase))
            {
                Console.WriteLine("Ignored modification to temporary or system file.");
            }
            else
            {
                // Invoke the delegate for other files if needed
            }
        }
    }
    

    Notez que la méthode ci-dessus ne réagit qu'aux modifications du fichier Excel spécifique et ignore les modifications des fichiers temporaires. Veuillez ajuster cette logique si vous avez des exigences différentes.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.