【问题标题】:Filesystemwatcher does not raise rename event handler in C# on Windows7Filesystemwatcher 不会在 Windows7 上的 C# 中引发重命名事件处理程序
【发布时间】:2010-09-16 14:53:42
【问题描述】:

我在 Windows 7 上使用 C# 3.5。我们已经实现了一个带有 FileSystemWatcher 的程序。在这里,不会引发重命名事件。但它正在一些系统上运行。

这可能是什么原因造成的?

【问题讨论】:

  • 您如何尝试引发重命名事件? BTW C# 3.5 不存在。
  • 嗨,我注意到在你提出的 10 个问题中,你没有接受一个关于堆栈溢出给你的答案......只是一个想法,这里都是关于社区的......: )
  • @klausbyskov - 是的,但是... Windows 的这个特定区域因不可靠而臭名昭著。我同意先寻找错误,但可能没有 100% 的解决方案。

标签: c# events .net-3.5


【解决方案1】:

您的代码中可能存在一个计时窗口,因此并非所有文件系统事件都可以在您的所有系统上正确捕获。可以发一下吗?

这是底层 Win32 API ReadDirectoryChangesW 和 FileSystemWatcher 的“功能”,在重负载下,可能会错过事件。 MSDN docs 中有缓解建议。

【讨论】:

    【解决方案2】:

    确保您设置了观察者:

    fileSystemWatcher.EnableRaisingEvents = true;
    

    【讨论】:

    • 如果没有设置,它在任何地方都不起作用。
    【解决方案3】:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Globalization;
    using System.IO;
    using System.Linq;
    using System.Security.AccessControl;
    using System.Security.Permissions;
    using System.Text;
    using System.Windows.Forms;
    
    namespace Watcher
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                FileRenamed();           
            }
    
            private static string _osLanguage = null;
            [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] 
    
            private void FileRenamed()
            {
                MessageBox.Show("Code is Started Now");
                // Create a new FileSystemWatcher and set its properties.
                FileSystemWatcher watcher = new FileSystemWatcher();
    
                SetDirectoryAccess(@"c:\temp");
    
                watcher.Path = @"C:\Temp";
    
                /* Watch for changes in LastAccess and LastWrite times, and
                   the renaming of files or directories. */
                watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                   | NotifyFilters.FileName | NotifyFilters.DirectoryName;
    
                // Only watch text files.
                watcher.Filter = "*.txt";
    
                // Add event handlers.
                watcher.Changed += new FileSystemEventHandler(OnChanged);
                watcher.Created += new FileSystemEventHandler(OnChanged);
                watcher.Deleted += new FileSystemEventHandler(OnChanged);
                watcher.Renamed += new RenamedEventHandler(OnRenamed);
                watcher.Error += new ErrorEventHandler(OnError);
    
                // Begin watching.
                watcher.EnableRaisingEvents = true;
    
            }
    
            // Define the event handlers.
            private static void OnChanged(object source, FileSystemEventArgs e)
            {
                // Specify what is done when a file is changed, created, or deleted.
                //Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
                MessageBox.Show("Something is changed in the File");
            }
    
            private static void OnRenamed(object source, RenamedEventArgs e)
            {
                // Specify what is done when a file is renamed.
                MessageBox.Show("File Is Renamed");
                //WatcherChangeTypes wct = e.ChangeType;
                //Console.WriteLine("File {0} {2} to {1}", e.OldFullPath, e.FullPath, wct.ToString());
            }
    
    
            //  This method is called when the FileSystemWatcher detects an error.
            private static void OnError(object source, ErrorEventArgs e)
            {
                MessageBox.Show("Error Trapped");
                //  Show that an error has been detected.
                Console.WriteLine("The FileSystemWatcher has detected an error");
                //  Give more information if the error is due to an internal buffer overflow.
                if (e.GetException().GetType() == typeof(InternalBufferOverflowException))
                {
                    //  This can happen if Windows is reporting many file system events quickly 
                    //  and internal buffer of the  FileSystemWatcher is not large enough to handle this
                    //  rate of events. The InternalBufferOverflowException error informs the application
                    //  that some of the file system events are being lost.
                    Console.WriteLine(("The file system watcher experienced an internal buffer overflow: " + e.GetException().Message));
                }
            }
    
    
            private void button1_Click(object sender, EventArgs e)
            {
                //File.Move(@"\\NAS\dossier_echange\Carl\temp\Test.txt", @"\\NAS\dossier_echange\Carl\temp\Test007.txt"); 
                File.Move(@"c:\temp\Test.txt", @"c:\temp\Test007.txt"); 
            }
    
            internal static void SetDirectoryAccess(string directoryPathString)
            {
                string everyoneString;
    
                if (OSLanguage.Equals("en-US"))
                    everyoneString = "Everyone";
                else
                    everyoneString = "Tout le monde";
    
                //sets the directory access permissions for everyone
                DirectorySecurity fileSecurity = Directory.GetAccessControl(directoryPathString);
                //creates the access rule for directory
                fileSecurity.ResetAccessRule(new FileSystemAccessRule(everyoneString, FileSystemRights.FullControl, AccessControlType.Allow));
                //sets the access rules for directory
                Directory.SetAccessControl(directoryPathString, fileSecurity);
            }
    
            public static string OSLanguage
            {
                get
                {
                    if (_osLanguage == null)
                        _osLanguage = CultureInfo.CurrentCulture.Name;
    
                    return _osLanguage;
                }
                set
                {
                    _osLanguage = value;
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多