private void StartFileWatcher()
        {
            /*
             * This is a very simple implementation.
             * Some improvements that could be made in the future:
             *
             * Watch all directories which contain assemblies that could be loaded
             * Support a polling file watcher.
             * Handle delete/recreate better.
             *
             * If you're interested in making improvements, feel free to send a pull request.
             */

            _debouncer = new Debouncer(_config.ReloadDelay);

            var watchedDir = Path.GetDirectoryName(_config.MainAssemblyPath);

            if (watchedDir == null)
            {
                throw new InvalidOperationException("Could not determine which directory to watch. "
                                                    + "Please set MainAssemblyPath to an absolute path so its parent directory can be discovered.");
            }

            _fileWatcher = new FileSystemWatcher
            {
                Path = watchedDir
            };
            _fileWatcher.Changed            += OnFileChanged;
            _fileWatcher.Filter              = "*.dll";
            _fileWatcher.NotifyFilter        = NotifyFilters.LastWrite;
            _fileWatcher.EnableRaisingEvents = true;
        }
示例#2
0
    public FileWatcher(string?watchedFile)
    {
        if (watchedFile is null)
        {
            return;
        }

        _watcher = new FileSystemWatcher()
        {
            NotifyFilter = NotifyFilters.FileName
                           | NotifyFilters.DirectoryName
                           //  | NotifyFilters.LastWrite
                           | NotifyFilters.LastAccess

            ,
            Path = Path.GetDirectoryName(watchedFile),
            IncludeSubdirectories = false,
            Filter = Path.GetFileName(watchedFile),
            EnableRaisingEvents = true,
        };
        _watcher.Changed += Watcher_Changed;
        _watcher.Renamed += Watcher_Renamed;
        //_watcher.Deleted += Watcher_Deleted;
        //_watcher.Created += _watcher_Created;
        _watcher.Error += Watcher_Error;
    }
        public SimpleFileWatcher(string dirToWatch, bool includeSubDirs, NotifyFilters notifyFilters, string fileFilter,
                                 FileSystemEventHandler?handler, RenamedEventHandler?renameHandler)
        {
            _fileWatcher = new FileSystemWatcher(dirToWatch)
            {
                IncludeSubdirectories = includeSubDirs,
                NotifyFilter          = notifyFilters,
                Filter = fileFilter
            };

            if (handler != null)
            {
                _fileWatcher.Created += handler;
                _fileWatcher.Deleted += handler;
                _fileWatcher.Changed += handler;
            }

            if (renameHandler != null)
            {
                _fileWatcher.Renamed += renameHandler;
            }

            _fileWatcher.EnableRaisingEvents = true;
            _handler       = handler;
            _renameHandler = renameHandler;
        }
示例#4
0
        private void CreateFileSystemWatcher()
        {
            lock (_createLock)
            {
                bool enableEvents = false;

                if (_fileSystemWatcher != null)
                {
                    enableEvents = _fileSystemWatcher.EnableRaisingEvents;

                    DisposeInnerWatcher();
                }

                _fileSystemWatcher = _watcherFactory(BasePath);
                _fileSystemWatcher.IncludeSubdirectories = true;

                _fileSystemWatcher.Created += WatcherChangeHandler;
                _fileSystemWatcher.Deleted += WatcherChangeHandler;
                _fileSystemWatcher.Changed += WatcherChangeHandler;
                _fileSystemWatcher.Renamed += WatcherRenameHandler;
                _fileSystemWatcher.Error   += WatcherErrorHandler;

                _fileSystemWatcher.EnableRaisingEvents = enableEvents;
            }
        }
示例#5
0
        private void EnsureFileSystemWatcherCreated(bool createDirectory)
        {
            if (m_FileSystemWatcher != null)
            {
                return;
            }

            if (!Directory.Exists(m_BasePath))
            {
                if (!createDirectory)
                {
                    return;
                }

                Directory.CreateDirectory(m_BasePath);
            }

            m_FileSystemWatcher = new FileSystemWatcher(m_BasePath)
            {
                IncludeSubdirectories = false,
                NotifyFilter          = NotifyFilters.LastWrite | NotifyFilters.CreationTime | NotifyFilters.Size,
                EnableRaisingEvents   = true
            };

            m_FileSystemWatcher.Changed += (_, args) =>
            {
                AsyncHelper.Schedule(
                    name: GetType().Name + "_" + nameof(ChangeEventHandler),
                    task: () => ChangeEventHandler(args),
                    ex => m_Logger?.LogError(ex, $"Error occured on file change for: {args.FullPath}"));
            };
        }
示例#6
0
    /// <summary>
    /// Main execution method for the Watch command. It starts a FileWatcher
    /// on the provided input directory. If anything changes, it fires off the
    /// `generate` command to rebuild
    /// </summary>
    /// <param name="app">App context</param>
    /// <returns>Status code</returns>
    public new async Task <int> OnExecuteAsync()
    {
        // normalize input path
        var inputPath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, InputDirectory));

        // build up FileWatcher and bind events
        _watcher          = new FileSystemWatcher(inputPath);
        _watcher.Renamed += async(s, e) => await Renamed(s, e);

        _watcher.Deleted += async(s, e) => await Changed(s, e);

        _watcher.Changed += async(s, e) => await Changed(s, e);

        _watcher.Created += async(s, e) => await Changed(s, e);

        _watcher.IncludeSubdirectories = true;
        _watcher.Filter = "";

        // run the initial generate command
        await RunGenerate();

        // keep running always until user closes
        while (true)
        {
            Thread.Sleep(10);
        }
        ;
    }
示例#7
0
        public Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogDebug("Starting data directory watcher");

            var root = _options.Value.DataDirectory;

            if (string.IsNullOrWhiteSpace(root))
            {
                _logger.LogInformation("No data directory set");
                return(Task.CompletedTask);
            }

            if (!_directory.Exists(root))
            {
                _logger.LogError("Data directory does not exist");
                return(Task.CompletedTask);
            }

            _logger.LogTrace("Creating filesystem watcher");
            _fileWatcher = new FileSystemWatcher(root)
            {
                EnableRaisingEvents   = true,
                IncludeSubdirectories = true,
            };

            _logger.LogTrace("Assigning filesystem watcher event handlers");
            CreateObservablesFromEvents(this, _fileWatcher);

            _logger.LogTrace("Finishing data directory watcher start");
            return(Task.CompletedTask);
        }
示例#8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FileSystemProvider"/> class.
        /// </summary>
        /// <param name="fileSystemPath">The file system path.</param>
        /// <param name="isImmutable"><see langword="true"/> if files and directories in
        /// <paramref name="fileSystemPath"/> are not expected to change during a web server's
        /// lifetime; <see langword="false"/> otherwise.</param>
        /// <exception cref="ArgumentNullException"><paramref name="fileSystemPath"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentException"><paramref name="fileSystemPath"/> is not a valid local path.</exception>
        /// <seealso cref="Validate.LocalPath"/>
        public FileSystemProvider(string fileSystemPath, bool isImmutable)
        {
            FileSystemPath = Validate.LocalPath(nameof(fileSystemPath), fileSystemPath, true);
            IsImmutable    = isImmutable;

            if (!IsImmutable)
            {
                _watcher = new FileSystemWatcher(FileSystemPath);
            }
        }
示例#9
0
 /// <summary>
 /// 監視を停止する
 /// </summary>
 public void UnWatch()
 {
     if (this.watcher is null)
     {
         return;
     }
     this.watcher.EnableRaisingEvents = false;
     this.watcher.Dispose();
     this.watcher = null;
 }
示例#10
0
        private void StopWatchingForFileSystemChanges()
        {
            if (m_watcher == null)
            {
                return;
            }

            m_watcher.Dispose();
            m_watcher = null;
        }
示例#11
0
 protected override void Dispose(bool disposing)
 {
     if (_watcher != null)
     {
         _watcher.Deleted -= OnFileDeleted;
         _watcher.Renamed -= OnFileDeleted;
         _watcher.Dispose();
         _watcher = null;
     }
     base.Dispose(disposing);
 }
示例#12
0
 private void WatchUserRuleFile(string workingDirectory)
 {
     UserRuleFileWatcher?.Dispose();
     UserRuleFileWatcher = new FileSystemWatcher(workingDirectory);
     UserRuleFileWatcher.NotifyFilter        = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
     UserRuleFileWatcher.Filter              = USER_RULE_FILE;
     UserRuleFileWatcher.Changed            += UserRuleFileWatcher_Changed;
     UserRuleFileWatcher.Created            += UserRuleFileWatcher_Changed;
     UserRuleFileWatcher.Deleted            += UserRuleFileWatcher_Changed;
     UserRuleFileWatcher.Renamed            += UserRuleFileWatcher_Changed;
     UserRuleFileWatcher.EnableRaisingEvents = true;
 }
示例#13
0
        /// <summary>
        /// Dispose 実装
        /// </summary>
        protected virtual void Dispose(bool disposing)
        {
            if (watcher != null)
            {
                if (disposing)
                {
                    watcher.Dispose();
                }

                watcher = null;
            }
        }
示例#14
0
 private void WatchPacFile(string workingDirectory)
 {
     PACFileWatcher?.Dispose();
     PACFileWatcher = new FileSystemWatcher(workingDirectory);
     PACFileWatcher.NotifyFilter        = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
     PACFileWatcher.Filter              = PAC_FILE;
     PACFileWatcher.Changed            += PACFileWatcher_Changed;
     PACFileWatcher.Created            += PACFileWatcher_Changed;
     PACFileWatcher.Deleted            += PACFileWatcher_Changed;
     PACFileWatcher.Renamed            += PACFileWatcher_Changed;
     PACFileWatcher.EnableRaisingEvents = true;
 }
示例#15
0
        /// <inheritdoc />
        public void Start()
        {
            _fileSystemWatcher = CreateFileSystemWatcher();

            // Register handlers for FileSystemWatcher events
            _fileSystemWatcher.Changed += InternalFileChangedHandler;
            _fileSystemWatcher.Created += InternalFileChangedHandler;
            _fileSystemWatcher.Deleted += InternalFileChangedHandler;
            _fileSystemWatcher.Renamed += InternalFileRenamedHandler;

            _fileSystemWatcher.EnableRaisingEvents = true;
        }
示例#16
0
        protected override void LoadContent()
        {
            Batch   = new(GraphicsDevice);
            Watcher = new()
            {
                Path = "Content",
                IncludeSubdirectories = true,
                EnableRaisingEvents   = true
            };
            Fonts = FontSystemFactory.CreateStroked(GraphicsDevice, 1);
            Fonts.AddFont(File.ReadAllBytes("Content/fonts/Montserrat-Medium.ttf"));

            base.LoadContent();
        }
示例#17
0
        public void Dispose()
        {
            RootFolder.Dispose();
            _package.Dispose();

            if (_watcher != null)
            {
                _watcher.Changed -= OnFileChange;
                _watcher.Deleted -= OnFileChange;
                _watcher.Renamed -= OnFileChange;
                _watcher.Dispose();
                _watcher = null;
            }
        }
示例#18
0
        public WatchingFileReaderProvider(ApplicationEvents events)
        {
            this.events = events;

            configFileWatcher = new FileSystemWatcher(GetConfigDirectory(), WatchedFilesFilter)
            {
                NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.LastAccess | NotifyFilters.DirectoryName | NotifyFilters.FileName
            };
            configFileWatcher.Created            += OnFileChanged;
            configFileWatcher.Changed            += OnFileChanged;
            configFileWatcher.Renamed            += (sender, e) => events.OnConfigurationChanged();
            configFileWatcher.Deleted            += (sender, e) => events.OnConfigurationChanged();
            configFileWatcher.EnableRaisingEvents = true;
        }
示例#19
0
 public void Start(string path, string filter)
 {
     if (watcher is null)
     {
         watcher = new FileSystemWatcher();
         watcher.NotifyFilter = NotifyFilters.LastWrite;
         watcher.Changed     += Watcher_Changed;
     }
     watcher.EnableRaisingEvents = false;
     watcher.Path   = path;
     watcher.Filter = filter;
     watcher.EnableRaisingEvents = true;
     logger.LogDebug("Started watching changes for file {File} in {Directory}", watcher.Filter, watcher.Path);
 }
        private void WatchPhysicalFile(DiskPackageFile physicalFile)
        {
            var folderPath = System.IO.Path.GetDirectoryName(physicalFile.OriginalPath);
            var fileName   = System.IO.Path.GetFileName(physicalFile.OriginalPath);

            _watcher = new FileSystemWatcher(folderPath, fileName)
            {
                IncludeSubdirectories = false,
                EnableRaisingEvents   = true
            };

            _watcher.Changed += OnFileChanged;
            _watcher.Deleted += OnFileDeleted;
            _watcher.Renamed += OnFileDeleted;
        }
        public InMemoryModelFactory(
            Lazy <UmbracoServices> umbracoServices,
            IProfilingLogger profilingLogger,
            ILogger <InMemoryModelFactory> logger,
            IOptionsMonitor <ModelsBuilderSettings> config,
            IHostingEnvironment hostingEnvironment,
            IApplicationShutdownRegistry hostingLifetime,
            IPublishedValueFallback publishedValueFallback,
            ApplicationPartManager applicationPartManager)
        {
            _umbracoServices        = umbracoServices;
            _profilingLogger        = profilingLogger;
            _logger                 = logger;
            _config                 = config.CurrentValue;
            _hostingEnvironment     = hostingEnvironment;
            _hostingLifetime        = hostingLifetime;
            _publishedValueFallback = publishedValueFallback;
            _applicationPartManager = applicationPartManager;
            _errors                 = new ModelsGenerationError(config, _hostingEnvironment);
            _ver     = 1;  // zero is for when we had no version
            _skipver = -1; // nothing to skip

            if (!hostingEnvironment.IsHosted)
            {
                return;
            }

            config.OnChange(x => _config = x);
            _pureLiveDirectory           = new Lazy <string>(PureLiveDirectoryAbsolute);

            if (!Directory.Exists(_pureLiveDirectory.Value))
            {
                Directory.CreateDirectory(_pureLiveDirectory.Value);
            }

            // BEWARE! if the watcher is not properly released then for some reason the
            // BuildManager will start confusing types - using a 'registered object' here
            // though we should probably plug into Umbraco's MainDom - which is internal
            _hostingLifetime.RegisterObject(this);
            _watcher                     = new FileSystemWatcher(_pureLiveDirectory.Value);
            _watcher.Changed            += WatcherOnChanged;
            _watcher.EnableRaisingEvents = true;

            // get it here, this need to be fast
            _debugLevel = _config.DebugLevel;

            AssemblyLoadContext.Default.Resolving += OnResolvingDefaultAssemblyLoadContext;
        }
示例#22
0
        public void TryCreateTeleporterWatcher(DalamudPluginInterface pi, bool useTeleport)
        {
            const string teleporterPluginConfigFile = "TeleporterPlugin.json";

            _teleporterLanguage = _language;
            if (!useTeleport || _teleporterWatcher != null)
            {
                _teleporterWatcher?.Dispose();
                _teleporterWatcher = null;
                return;
            }

            var dir = new DirectoryInfo(pi.GetPluginConfigDirectory());

            if (!dir.Exists || (dir.Parent?.Exists ?? false))
            {
                return;
            }

            dir = dir.Parent;

            var file = new FileInfo(Path.Combine(dir !.FullName, teleporterPluginConfigFile));

            if (file.Exists)
            {
                ParseTeleporterFile(file.FullName);
            }

            void OnTeleporterConfigChange(object source, FileSystemEventArgs args)
            {
                PluginLog.Verbose("Reloading Teleporter Config.");
                if (args.ChangeType != WatcherChangeTypes.Changed && args.ChangeType != WatcherChangeTypes.Created)
                {
                    return;
                }

                ParseTeleporterFile(args.FullPath);
            }

            _teleporterWatcher = new FileSystemWatcher
            {
                Path         = dir.FullName,
                NotifyFilter = NotifyFilters.LastWrite,
                Filter       = teleporterPluginConfigFile,
            };
            _teleporterWatcher.Changed += OnTeleporterConfigChange;
            _teleporterWatcher !.EnableRaisingEvents = true;
        }
示例#23
0
        /// <summary>
        /// 監視する
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="filters"></param>
        /// <param name="handler"></param>
        public void Watch(string filePath, NotifyFilters filters, Action <FileSystemEventArgs> handler)
        {
            if (this.watcher is not null)
            {
                throw new InvalidOperationException("すでに監視しています。");
            }

            string dirPath  = Path.GetDirectoryName(filePath) !;
            string fileName = Path.GetFileName(filePath) !;

            this.watcher = new FileSystemWatcher(dirPath);
            this.watcher.NotifyFilter        = filters;
            this.watcher.Filter              = fileName;
            this.watcher.Changed            += (_, e) => handler(e);
            this.watcher.EnableRaisingEvents = true;
        }
示例#24
0
        private void StartDirectoryWatcher()
        {
            _fileSystemWatcher = new FileSystemWatcher(_game.LogsDirectory !)
            {
                NotifyFilter = NotifyFilters.DirectoryName
            };
            _fileSystemWatcher.Created += async(s, e) =>
            {
                _fileSystemWatcher.EnableRaisingEvents = false;

                await Stop();
                await Start();
            };
            _fileSystemWatcher.EnableRaisingEvents = true;
        }
    }
示例#25
0
 /// <summary>
 /// file change watcher
 /// </summary>
 /// <param name="path">The directory to monitor, in standard or Universal Naming Convention (UNC) notation</param>
 /// <param name="filter">The type of files to watch. For example, "*.txt" watches for changes to all text files.</param>
 public static void WatchFiles(string path, string filter)
 {
     if (!Directory.Exists(path))
     {
         throw new FileNotFoundException();
     }
     s_watcher = new FileSystemWatcher(path, filter)
     {
         IncludeSubdirectories = true
     };
     s_watcher.Created            += OnFileChanged;
     s_watcher.Changed            += OnFileChanged;
     s_watcher.Deleted            += OnFileChanged;
     s_watcher.Renamed            += OnFileRenamed;
     s_watcher.EnableRaisingEvents = true;
     Console.WriteLine("watching file changes ...");
 }
示例#26
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FileSystemProvider"/> class.
        /// </summary>
        /// <remarks>
        /// OSX doesn't support <see cref="FileSystemWatcher" />, the parameter <paramref name="isImmutable" /> will be always <see langword="true"/>.
        /// </remarks>
        /// <param name="fileSystemPath">The file system path.</param>
        /// <param name="isImmutable"><see langword="true"/> if files and directories in
        /// <paramref name="fileSystemPath"/> are not expected to change during a web server's
        /// lifetime; <see langword="false"/> otherwise.</param>
        /// <exception cref="ArgumentNullException"><paramref name="fileSystemPath"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentException"><paramref name="fileSystemPath"/> is not a valid local path.</exception>
        /// <seealso cref="Validate.LocalPath"/>
        public FileSystemProvider(string fileSystemPath, bool isImmutable)
        {
            FileSystemPath = Validate.LocalPath(nameof(fileSystemPath), fileSystemPath, true);
            IsImmutable    = isImmutable || RuntimeInformation.IsOSPlatform(OSPlatform.OSX);

            try
            {
                if (!IsImmutable)
                {
                    _watcher = new FileSystemWatcher(FileSystemPath);
                }
            }
            catch (PlatformNotSupportedException)
            {
                IsImmutable = true;
            }
        }
示例#27
0
        private void CreateFileSystemWatcher()
        {
            m_FileSystemWatcher = new FileSystemWatcher(m_BasePath)
            {
                IncludeSubdirectories = false,
                NotifyFilter          = NotifyFilters.LastWrite | NotifyFilters.CreationTime | NotifyFilters.Size,
                EnableRaisingEvents   = true
            };

            m_FileSystemWatcher.Changed += (_, a) =>
            {
                try
                {
                    if (a.ChangeType == WatcherChangeTypes.Renamed ||
                        a.ChangeType == WatcherChangeTypes.Deleted)
                    {
                        return;
                    }

                    foreach (var key in m_KnownKeys)
                    {
                        var filePath = GetFilePathForKey(key);

                        if (!a.FullPath.Equals(Path.GetFullPath(filePath), StringComparison.Ordinal))
                        {
                            continue;
                        }

                        lock (GetLock(key))
                        {
                            if (DecrementWriteCounter(key))
                            {
                                m_Logger.LogDebug($"File changed: {a.FullPath} ({a.ChangeType:X})");
                                OnFileChange(key);
                            }
                        }

                        return;
                    }
                }
                catch (Exception ex)
                {
                    m_Logger.LogError(ex, $"Error occured on file change for: {a.FullPath}");
                }
            };
        }
示例#28
0
        /// <summary>
        /// Disposes of every reference that must be cleaned up.
        /// </summary>
        private void DisposeNow()
        {
            using (UpdateMoonPhaseTimer)
            {
                UpdateMoonPhaseTimer.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
            }

            using (UpdateMushroomNameListTimer)
            {
                UpdateMushroomNameListTimer.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
            }

            if (MushroomNameFileWatcher != null)
            {
                MushroomNameFileWatcher.EnableRaisingEvents = false;
                MushroomNameFileWatcher.Dispose();
                MushroomNameFileWatcher = null;
            }
        }
示例#29
0
        public override Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Service Starting");
            if (!Directory.Exists(_inputFolder))
            {
                _logger.LogWarning("Please make sure the InputFolder [{inputFolder}] exists, then restart the service.", _inputFolder);
                return(Task.CompletedTask);
            }

            _logger.LogInformation("Binding Events from Input Folder: {inputFolder}", _inputFolder);
            _folderWatcher = new FileSystemWatcher(_inputFolder, "*.TXT")
            {
                NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite | NotifyFilters.FileName |
                               NotifyFilters.DirectoryName
            };
            _folderWatcher.Created            += Input_OnChanged;
            _folderWatcher.EnableRaisingEvents = true;

            return(base.StartAsync(cancellationToken));
        }
示例#30
0
 public void Dispose()
 {
     if (_fileWatcher != null)
     {
         _fileWatcher.EnableRaisingEvents = false;
         if (_handler != null)
         {
             _fileWatcher.Created -= _handler;
             _fileWatcher.Deleted -= _handler;
             _fileWatcher.Changed -= _handler;
             _handler              = null;
         }
         if (_renameHandler != null)
         {
             _fileWatcher.Renamed -= _renameHandler;
             _renameHandler        = null;
         }
         _fileWatcher.Dispose();
         _fileWatcher = null;
     }
 }