【问题标题】:FileSystemWatcher for FTP not notifying when a new file is added to folder当新文件添加到文件夹时,FTP 的 FileSystemWatcher 不通知
【发布时间】:2020-12-23 21:46:52
【问题描述】:

我在 Windows 控制台应用程序中运行我的程序,但我已经在网络上映射了一个 NFS 驱动器,我在 Linux 机器上通过 SFTP 下载文件。当我的 shellscript 将文件带回该文件夹时,我的应用程序不会在文件到达时捕获,但如果我从 Windows 或 Linux 复制文件,它工作正常。几乎就像 FileSystemWatcher 来自 SFTP 脚本时不起作用一样。

这里是代码示例

Global.MainPath = Console.ReadLine();
p.path = Global.MainPath;
MonitorDirectory(p.path);
Console.WriteLine("Checking folder " + p.path);
Console.WriteLine(" ");

while (true)
{
    MonitorDirectory(p.path);
    ShowContent(p.path);
    Console.WriteLine(" ");
    Console.Write("Enter q to quit: ");
    line = Console.ReadLine().ToLower();
    if (line == "q" || line == "quit")
    {
        break;
    }
    else
    {
        Console.Clear();
    }
}

// and here's the MonitorDirectory & FileSystemWatcher_Created methods

private static void MonitorDirectory(string path)
{
    FileSystemWatcher fileSystemWatcher = new FileSystemWatcher
    { Path = path };
    fileSystemWatcher.Created += FileSystemWatcher_Created;
    fileSystemWatcher.Renamed += FileSystemWatcher_Renamed;
    fileSystemWatcher.Deleted += FileSystemWatcher_Deleted;
    fileSystemWatcher.Changed += FileSystemWatcher_Changed;
    fileSystemWatcher.EnableRaisingEvents = true;
 }

private static void FileSystemWatcher_Created(object sender, FileSystemEventArgs e)
{
    Mypath p = new Mypath();
    Console.Clear();
    p.path = Global.MainPath;
    string filePath = p.path + "\\" + e.Name;
    Console.WriteLine("File created: {0}", e.Name);
    SendEmailtoContacts("File Created " + e.Name, filePath + " has been created from the folder");
    ShowContent(p.path);
}

【问题讨论】:

  • “但如果我从 Windows 或 Linux 复制文件,它可以正常工作” – 不清楚您将文件复制到何处以及复制到何处。请具体。您还可以混合使用 SFTP 和 FTP。这些是完全不同的事情。我认为您的问题与您的代码或FileSystemWatcher 无关。它更多地是关于运行网络共享的系统。你没有告诉我们太多。如果您在 Windows 资源管理器中打开 NFS 驱动器会怎样。它是否检测到何时使用您的 (S)FTP 脚本添加/修改了文件?
  • 您应该添加一些错误处理,以确保您的代码至少可以按预期工作而没有任何错误
  • 也许只有我一个人,但除了@Joey 在下面提出的要点之外,我会将FileSystemWatcherMonitorDirectory 方法中提取出来(它目前是一个局部变量)并实现它班级成员(和@Joey 一样,我会跳过static-ness)

标签: c# linux sftp filesystemwatcher


【解决方案1】:

您在每个循环中都重新初始化了系统文件观察程序。 删除这个:

MonitorDirectory(p.path);

来自循环。

顺便说一句:我不会使用静态方法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多