我的 docker 容器内的程序使用 FileSystemWatcher 来监视本地文件夹。我用以下命令安装了目录:
docker run -v /c/Users/Support/Desktop/inbox:/Users/Support/Desktop/inbox -v /c/Users/Support/Desktop/outbox:/Users/Support/Desktop/outbox -it --name workbean运行workbean
我使用 Docker Exec 在容器运行时查看该容器。它可以查看收件箱和发件箱目录以及其中的任何文件。但是,当我将新文件放入收件箱时,FileSystemWatcher 事件不会触发。代码没有任何问题,因为如果我不使用 docker 容器,它运行得很好。
安装目录时我还需要做什么吗?或者 FileSystemWatcher 甚至可以在容器内吗?
好的,按照要求,程序如下:
using System;
using System.IO;
namespace workbean
{
class Program
{
FileSystemWatcher watcher = new FileSystemWatcher();
static string sourceDir = "/Users/Support/Desktop/inbox";
static string destDir = "/Users/Support/Desktop/outbox";
static void Main(string[] args)
{
Console.WriteLine("Testing...");
Program p = new Program();
while (true) { }
}
public Program()
{
watcher.Path = sourceDir;
watcher.Filter = "*.*";
watcher.Created += new FileSystemEventHandler(OnCreated);
watcher.EnableRaisingEvents = true;
}
static void OnCreated(object source, FileSystemEventArgs e)
{
string[] files = Directory.GetFiles(sourceDir);
foreach (var item in files)
{
string destDir2 = destDir + "/" + Path.GetFileName(item);
File.Move(item, destDir2);
}
}
}
}
看来这就是正在发生的事情:
本地驱动器上的收件箱文件夹与容器中的收件箱文件夹相关联。如果您将文件添加到其中一个,它们就会显示在另一个中。
但是,FileSystemWatcher 仅监视容器中的收件箱。如果我将文件添加到容器中的收件箱,则 FileSystemWatcher 会触发一个事件。
但是,当将文件添加到本地收件箱时,没有任何反应,因为 FileSystemWatcher 没有监视该文件,即使这两个文件夹彼此绑定。