【问题标题】:FileSystemWatcher doesn't seem trigger under ASP.NETFileSystemWatcher 似乎没有在 ASP.NET 下触发
【发布时间】:2018-07-25 17:16:50
【问题描述】:

我正在尝试监视我的 asp.net mvc5 项目中的文件夹。我想把它放在我初始化 FileSystemWatcher 的 Startup.cs 中。

public static void initializeWatcher()
    {
        string importPath = @"\\server\Exchange\Inbox", importFilterType = "*.xml";
        try
        {
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = importPath;
            watcher.Filter = ".xml";
            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName;
            watcher.Created += new FileSystemEventHandler(loadFile);
            watcher.Changed += new FileSystemEventHandler(loadFile);
            watcher.EnableRaisingEvents = true;
        }
        catch (Exception e)
        {

        }
    }

    private static void loadFile(object source, FileSystemEventArgs e)
    {
        xmlDocument.LoadXml(e.FullPath);
    }
}

现在,观察者被创建,但“loadFile”方法没有被触发,无论我在文件夹中做什么。 我按照微软的例子: https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(v=vs.110).aspx

让我知道我做错了什么。

【问题讨论】:

  • 您将 FSW 存储在局部变量中。这意味着一旦执行离开方法,它将被垃圾收集。至少将其存储到静态字段中。不过,这个问题与 Hangfire 有什么关系?
  • 顺便说一句,为什么 catch (Exception e){} 块?如果有任何例外情况,您不会得到一个正常工作的 FSW 吗?
  • catch 块仅用作预防措施。
  • 我从 Hangfire 开始,后来把它拿出来忘记了我提到的 Hangfire。

标签: c# asp.net


【解决方案1】:

您似乎将FileSystemWatcher 创建为方法中的局部变量。这当然会在方法结束时超出范围,并且很可能在那时被整理,然后删除手表。

尝试在 Startup.cs 中将 FSW 创建为私有对象

public class Startup
{
    private FileSystemWatcher watcher {get;set;}

    public Startup(IApplicationEnvironment env,
               IHostingEnvironment hostenv,  ILoggerFactory logger)
    {
       //your setup FSW
    {
}

接下来,尝试只使用NotifyFilters.LastWrite

【讨论】:

  • 我已将 FileSystemWatcher 作为私有属性添加到类“Startup”,并将初始化行添加到方法 Configuration。我还添加了方法 loadFile,当文件被创建或更改为“启动”类时应该触发该方法,并为其设置断点。但什么也没发生。
  • 就我而言;我只使用 NotifyFilter = NotifyFilters.LastWrite。你能试试这个吗
猜你喜欢
  • 2012-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-26
  • 1970-01-01
  • 2016-11-09
  • 2021-06-14
相关资源
最近更新 更多