c# FileSystemWatcher Created 事件不会为所有创建的文件触发

c# FileSystemWatcher Created event not firing for all files created

我想将在目录中创建的所有文件的文件信息插入到数据库中。如果我在目录中放置少量文件,我的程序将执行此操作,但如果我一次在目录中放置大量文件,它不会全部获取它们(我没有做大量测试,但它只插入了大约当我试图一次将 800 个文件放入目录时,我的数据库中有 200 个名称)。

这是我的代码:

static void Main(string[] args)
{
    // Create a new FileSystemWatcher and set its properties.
    FileSystemWatcher watcher = new FileSystemWatcher();
    watcher.Path = @"C:\dropDirectory";

    // Add event handlers.
    watcher.Created += new FileSystemEventHandler(OnChanged);

    // Begin watching.
    watcher.EnableRaisingEvents = true;

    while(DateTime.Now.Hour < 10);
}

private static void OnChanged(object source, FileSystemEventArgs e)
{
    string strInsert = "INSERT INTO  Files (Filename) VALUES ('" + e.Name + "')";
    string strConnection = "Server = server_name; Database = database_name; User Id = user_id; Password = password;";
    using (SqlConnection con = new SqlConnection(strConnection))
    {
        using (SqlCommand cmd = new SqlCommand(strInsert, con))
        {   
            con.Open();
            cmd.ExecuteScalar();
        }
    }
}

我需要进行哪些更改,以便无论一次删除多少文件,都会为目标目录中删除的每个文件调用我的 OnChanged 方法?提前致谢。

您的问题是缓冲区大小,这是一个众所周知的记录问题

FileSystemWatcher 使用 ReadDirectoryChangesW WinApi 调用和一些相关标志

When you first call ReadDirectoryChangesW, the system allocates a buffer to store change information. This buffer is associated with the directory handle until it is closed and its size does not change during its lifetime. Directory changes that occur between calls to this function are added to the buffer and then returned with the next call. If the buffer overflows, the entire contents of the buffer are discarded

FileSystemWatcher 中的类似物是 FileSystemWatcher.InternalBufferSize 属性

Remarks You can set the buffer to 4 KB or larger, but it must not exceed 64 KB. If you try to set the InternalBufferSize property to less than 4096 bytes, your value is discarded and the InternalBufferSize property is set to 4096 bytes. For best performance, use a multiple of 4 KB on Intel-based computers.

The system notifies the component of file changes, and it stores those changes in a buffer the component creates and passes to the APIs. Each event can use up to 16 bytes of memory, not including the file name. If there are many changes in a short time, the buffer can overflow. This causes the component to lose track of changes in the directory, and it will only provide blanket notification. Increasing the size of the buffer can prevent missing file system change events. However, increasing buffer size is expensive, because it comes from non-paged memory that cannot be swapped out to disk, so keep the buffer as small as possible. To avoid a buffer overflow, use the NotifyFilter and IncludeSubdirectories properties to filter out unwanted change notifications.

如果情况变得更糟,您可以结合使用轮询和跟踪,它帮助我摆脱了几次麻烦。