Inheritance: Component, ISupportInitialize
示例#1
0
        private static System.IO.FileSystemWatcher CreateWatcher(string dir, BlockingCollection <string> files)
        {
            var watcher = new System.IO.FileSystemWatcher(dir, "*.cs")
            {
                IncludeSubdirectories = true, InternalBufferSize = 1000000
            };

            System.IO.FileSystemEventHandler handler = (_s, _e) =>
            {
                Console.WriteLine(_e.FullPath);
                Console.WriteLine("  {0}, {1}", _e.ChangeType, _e.Name);
                if (!_e.Name.EndsWith(".cs", StringComparison.InvariantCultureIgnoreCase))
                {
                    return;
                }
                files.TryAdd(_e.FullPath);
            };
            watcher.Changed            += handler;
            watcher.Created            += handler;
            watcher.Deleted            += handler;
            watcher.Renamed            += (_s, _e) => handler(_s, _e);
            watcher.NotifyFilter        = System.IO.NotifyFilters.FileName;
            watcher.EnableRaisingEvents = true;

            return(watcher);
        }
示例#2
0
 public void Add(string dir, string filter)
 {
     var fsw = new FileSystemWatcher(dir, filter);
     fsw.NotifyFilter = NotifyFilters.LastWrite;
     fsw.Changed += OnFileChanged;
     fsw.EnableRaisingEvents = true;
 }
示例#3
0
        public InputTranParser(LuaFixTransactionMessageAdapter transAdapter, FixMessageAdapter messAdapter, List<Security> securities)
        {
            _transAdapter = transAdapter;
            _messAdapter = messAdapter;
            _securities = securities;

            _watcher = new FileSystemWatcher(_tranFilePath, "*.tri");

            _tranKeys = new List<TransactionKey>
            {
                new TransIdKey(),
                new AccountKey(),
                new ClientCodeKey(),
                new ClassCodeKey(),
                new SecCodeKey(),
                new ActionKey(),
                new OperationKey(),
                new PriceKey(),
                new StopPriceKey(),
                new QuantityKey(),
                new TypeKey(),
                new OrderKeyKey(),
                new OriginalTransIdKey(),
                new CommentKey()
            };
        }
示例#4
0
        public async Task WillReindexAfterCrashing(string storage)
        {
            int port = 9999;
            var filesystem = Path.GetRandomFileName();
            var nameof = "WillReindexAfterCrashing-" + DateTime.Now.Ticks;

            string dataDirectoryPath;
            using (var server = CreateServer(port, dataDirectory: nameof, runInMemory: false, requestedStorage: storage))
            {
                dataDirectoryPath = server.Configuration.DataDirectory;

                var store = server.FilesStore;
                await store.AsyncFilesCommands.Admin.EnsureFileSystemExistsAsync(filesystem);

                using (var session = store.OpenAsyncSession(filesystem))
                {
                    session.RegisterUpload("test1.file", CreateUniformFileStream(128));
                    session.RegisterUpload("test2.file", CreateUniformFileStream(128));
                    session.RegisterUpload("test3.file.deleting", CreateUniformFileStream(128));
                    await session.SaveChangesAsync();
                }
            }

            // Simulate a rude shutdown.
            var filesystemDirectoryPath = Path.Combine(dataDirectoryPath, "FileSystems");
            var crashMarkerPath = Path.Combine(filesystemDirectoryPath, filesystem, "indexing.crash-marker");
            using (var file = File.Create(crashMarkerPath)) { };
            var writingMarkerPath = Path.Combine(filesystemDirectoryPath, filesystem, "Indexes", "writing-to-index.lock");
            using (var file = File.Create(writingMarkerPath)) { };

            bool changed = false;

            // Ensure the index has been reseted.            
            var watcher = new FileSystemWatcher(Path.Combine(filesystemDirectoryPath, filesystem));
            watcher.IncludeSubdirectories = true;
            watcher.Deleted += (sender, args) => changed = true;
            watcher.EnableRaisingEvents = true;

            using (var server = CreateServer(port, dataDirectory: nameof, runInMemory: false, requestedStorage: storage))
            {
                var store = server.FilesStore;

                using (var session = store.OpenAsyncSession(filesystem))
                {
                    // Ensure the files are there.
                    var file1 = await session.LoadFileAsync("test1.file");
                    Assert.NotNull(file1);

                    // Ensure the files are indexed.
                    var query = await session.Query()
                                             .WhereStartsWith(x => x.Name, "test")
                                             .ToListAsync();

                    Assert.True(query.Any());
                    Assert.Equal(2, query.Count());
                }
            }

            Assert.True(changed);
        }
示例#5
0
        public void Setup(int delay, System.Collections.IList assemblies)
#endif
		{
            log.Info("Setting up watcher");

			files = new FileInfo[assemblies.Count];
			fileWatchers = new FileSystemWatcher[assemblies.Count];

			for (int i = 0; i < assemblies.Count; i++)
			{
                log.Debug("Setting up FileSystemWatcher for {0}", assemblies[i]);
                
				files[i] = new FileInfo((string)assemblies[i]);

				fileWatchers[i] = new FileSystemWatcher();
				fileWatchers[i].Path = files[i].DirectoryName;
				fileWatchers[i].Filter = files[i].Name;
				fileWatchers[i].NotifyFilter = NotifyFilters.Size | NotifyFilters.LastWrite;
				fileWatchers[i].Changed += new FileSystemEventHandler(OnChanged);
				fileWatchers[i].EnableRaisingEvents = false;
			}

			timer = new System.Timers.Timer(delay);
			timer.AutoReset = false;
			timer.Enabled = false;
			timer.Elapsed += new ElapsedEventHandler(OnTimer);
		}
示例#6
0
        public ScriptManager()
        {
            LoadScripts();

            watcher = new FileSystemWatcher(Config.GetValue(ConfigSections.DEV, ConfigValues.SCRIPT_LOCATION))
                          {
                              NotifyFilter =
                                  NotifyFilters
                                      .LastAccess
                                  | NotifyFilters
                                        .LastWrite
                                  | NotifyFilters
                                        .FileName
                                  | NotifyFilters
                                        .DirectoryName,
                              Filter =
                                  "*.cs"
                          };

            watcher.Changed += ReloadScript;
            watcher.Created += LoadScript;
            watcher.Renamed += LoadScript;
            watcher.Deleted += UnloadScript;

            watcher.EnableRaisingEvents = true;
        }
        protected override void OnStart(string[] args)
        {
            if (!EventLog.SourceExists("SSISIncomingDirectoryWatcher", "."))
            {
                EventLog.CreateEventSource("SSISIncomingDirectoryWatcher", "Application");
            }

            Lg = new EventLog("Application", ".", "SSISIncomingDirectoryWatcher");
            Lg.WriteEntry("Service started at " + DateTime.Now, EventLogEntryType.Information);

            try
            {

                tw = File.CreateText(logFilePath);
                tw.WriteLine("Service started at {0}", DateTime.Now);
                readInConfigValues();
                Watcher = new FileSystemWatcher();
                Watcher.Path = dirToWatch;
                Watcher.IncludeSubdirectories = false;
                Watcher.Created += new FileSystemEventHandler(watcherChange);
                Watcher.EnableRaisingEvents = true;
            }
            catch (Exception ex)
            {
                Lg.WriteEntry(ex.Message, EventLogEntryType.Error);
            }
            finally
            {
                tw.Close();
            }
        }
示例#8
0
        int TimerDue = 1000 * 60 * 60 * 24;         // 24 hours

        public DiskManager()
        {
            userWatcher = new System.IO.FileSystemWatcher(userTemp);
            userWatcher.NotifyFilter = System.IO.NotifyFilters.Size;
            userWatcher.Deleted     += ModifyTemp;
            userWatcher.Created     += ModifyTemp;
            if (systemTemp != userTemp)
            {
                sysWatcher = new System.IO.FileSystemWatcher(systemTemp);
                sysWatcher.NotifyFilter = System.IO.NotifyFilters.Size;
                sysWatcher.Deleted     += ModifyTemp;
                sysWatcher.Created     += ModifyTemp;
            }

            TempScanTimer = new System.Timers.Timer(TimerDue);
            ScanTemp();
            TempScanTimer.Elapsed += async(s, e) => { await ScanTemp().ConfigureAwait(false); };
            TempScanTimer.Start();

            Log.Information("<Maintenance> Temp folder scanner will be performed once per day.");

            onBurden += ReScanTemp;

            Log.Information("<Maintenance> Component loaded.");
        }
示例#9
0
        public async Task Start()
        {
            _isWatching = true;

            using (System.IO.FileSystemWatcher fileSystemWatcher = new System.IO.FileSystemWatcher(FolderPath))
            {
                fileSystemWatcher.IncludeSubdirectories = true;

                fileSystemWatcher.NotifyFilter =
                    NotifyFilters.Attributes |
                    NotifyFilters.DirectoryName;

                fileSystemWatcher.Changed += FileSystemWatcher_Changed;
                fileSystemWatcher.Created += FileSystemWatcher_Created;
                fileSystemWatcher.Deleted += FileSystemWatcher_Deleted;
                fileSystemWatcher.Error   += FileSystemWatcher_Error;
                fileSystemWatcher.Renamed += FileSystemWatcher_Renamed;

                fileSystemWatcher.EnableRaisingEvents = true;

                await Task.Run(() =>
                {
                    while (_isWatching)
                    {
                        ;
                    }
                });
            }
        }
        private void StartWatcher()
        {
            watcher      = new System.IO.FileSystemWatcher();
            watcher.Path = TbDirectory.Text;

            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                                   | NotifyFilters.FileName | NotifyFilters.DirectoryName;

            // Watch Specific File Types
            if (!CbDirectory.Text.Equals(""))
            {
                watcher.Filter = CbDirectory.Text;
            }//end if

            // Add event handlers.
            watcher.Changed += new FileSystemEventHandler(OnChanged);
            watcher.Created += new FileSystemEventHandler(OnChanged);
            watcher.Deleted += new FileSystemEventHandler(OnChanged);
            watcher.Renamed += new RenamedEventHandler(OnRenamed);

            // Begin watching.
            watcher.EnableRaisingEvents = true;

            watcher.IncludeSubdirectories = true;
        }//end Watcher
        private static System.IO.FileSystemWatcher CreateFileSystemWatcher(string path, NotifyFilters notifyFilters, string fileFilter, bool includeSubDirectories, int internalBufferSize)
        {
            System.IO.FileSystemWatcher watcher = new System.IO.FileSystemWatcher
            {
                Path = path,
                EnableRaisingEvents   = true,
                IncludeSubdirectories = includeSubDirectories,
                NotifyFilter          = notifyFilters,
            };

            if (!string.IsNullOrWhiteSpace(fileFilter))
            {
                watcher.Filter = fileFilter;
            }
            else
            {
                watcher.Filter = _defaultFileFilter;
            }
            if (internalBufferSize > 0)
            {
                watcher.InternalBufferSize = internalBufferSize;
            }

            return(watcher);
        }
示例#12
0
        public BackUpSystem(string tracking_directory, string backup_directory, string filter, bool IsTracking)
        {
            this.tracking_directory = tracking_directory;
            this.backup_directory   = backup_directory;
            this.filter             = filter;
            logger_fullpath         = Path.Combine(backup_directory, "logger.txt");
            if (!Directory.Exists(backup_directory) || !File.Exists(logger_fullpath))
            {
                Directory.CreateDirectory(backup_directory);
                string[] files_in_backup = Directory.GetFiles(backup_directory);
                foreach (var file in files_in_backup)
                {
                    File.Delete(file);
                }
                (File.Create(logger_fullpath)).Close();

                string[] all_tracking_files = Directory.GetFiles(tracking_directory, "*" + filter, SearchOption.AllDirectories);
                Save("Created", all_tracking_files);
            }
            else
            {
                var c = Directory.GetFiles(this.backup_directory, "BackUp*" + filter, SearchOption.AllDirectories);
                files_count = c.Length;
            }

            filewatcher = new FileSystemWatcher(tracking_directory);
            filewatcher.IncludeSubdirectories = true;
            filewatcher.Changed            += FileSystemWatcher_OnChanged;
            filewatcher.Created            += FileSystemWatcher_OnCreated;
            filewatcher.Deleted            += FileSystemWatcher_OnCreated;
            filewatcher.Renamed            += FileSystemWatcher_OnRenamed;
            filewatcher.Error              += FileSystemWatcher_OnError;
            filewatcher.EnableRaisingEvents = IsTracking;
        }
示例#13
0
        void StartWatch(string PathToWatch, string Filter, bool IncludeSubdirectories)
        {
            m_bIsWatching = true;

            m_Watcher        = new System.IO.FileSystemWatcher();
            m_Watcher.Filter = Filter; // "*.*";
            if (PathToWatch[PathToWatch.Length - 1] != '\\')
            {
                m_Watcher.Path = PathToWatch + "\\"; // txtFile.Text + "\\";
            }
            else
            {
                m_Watcher.Path = PathToWatch;
            }

            m_Watcher.IncludeSubdirectories = IncludeSubdirectories;


            m_Watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                                     | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            m_Watcher.Changed            += new FileSystemEventHandler(OnChanged);
            m_Watcher.Created            += new FileSystemEventHandler(OnCreated);
            m_Watcher.Deleted            += new FileSystemEventHandler(OnDelete);
            m_Watcher.Renamed            += new RenamedEventHandler(OnRenamed);
            m_Watcher.EnableRaisingEvents = true;
        }
示例#14
0
        private void InitFileSystemWatcher()
        {
            Info("Initializing FileSystemWatcher...");
            Watcher = new IO.FileSystemWatcher
            {
                Path   = FolderToWatch,
                Filter = Filter,
                IncludeSubdirectories = IncludeSubFolders
            };

            // Add event handlers.
            Watcher.Created += OnCreated;
            Watcher.Changed += OnChanged;
            Watcher.Deleted += OnDeleted;

            // Begin watching.
            Watcher.EnableRaisingEvents = true;
            InfoFormat("FileSystemWatcher.Path={0}", Watcher.Path);
            InfoFormat("FileSystemWatcher.Filter={0}", Watcher.Filter);
            InfoFormat("FileSystemWatcher.EnableRaisingEvents={0}", Watcher.EnableRaisingEvents);
            Info("FileSystemWatcher Initialized.");

            Info("Begin watching ...");
            CurrentLogs.AddRange(Logs);
            while (true)
            {
                Thread.Sleep(1);
            }
        }
        public ViewLabels()
        {
            _labelTemplateManager = FirstFloor.ModernUI.App.App.Container.GetInstance<ILabelTemplateManager>();
            _labelManager = FirstFloor.ModernUI.App.App.Container.GetInstance<ILabelManager>();
            _bitmapGenerator = FirstFloor.ModernUI.App.App.Container.GetInstance<IBitmapGenerator>();
            _fileManager = FirstFloor.ModernUI.App.App.Container.GetInstance<IFileManager>();

            _labelLocation = new CommandLineArgs()["location"];
            LabelImages = new ObservableCollection<DisplayLabel>();
     
            InitializeComponent();

            DataContext = this;

            var configDirectory = $@"{AppDomain.CurrentDomain.BaseDirectory}\Config\";
            if (_fileManager.CheckDirectoryExists(configDirectory))
            {
                _fsWatcher = new FileSystemWatcher
                {
                    NotifyFilter = NotifyFilters.LastWrite,
                    Path = configDirectory,
                    Filter = "labels.json",
                    EnableRaisingEvents = true
                };
                _fsWatcher.Changed += FsWatcherOnChanged;

                GetImages();
            }
            else
            {
                ModernDialog.ShowMessage($"An error occurred. The '{configDirectory}' directory could not be found.", "Error", MessageBoxButton.OK, Window.GetWindow(this));

            }
            
        }
示例#16
0
 public void Add(string dir, string filter)
 {
     System.IO.FileSystemWatcher fsw = new System.IO.FileSystemWatcher(dir, filter);
     fsw.NotifyFilter        = System.IO.NotifyFilters.LastWrite;
     fsw.Changed            += new FileSystemEventHandler(OnFileChanged);
     fsw.EnableRaisingEvents = true;
 }
示例#17
0
        public string StartWatchWrongFiles(string PathToWatch, bool IncludeSubdirectories)
        {
            try
            {
                if (m_WatcherWrong != null)
                {
                    StopWatchWrongFiles();
                }
                m_WatcherWrong        = new System.IO.FileSystemWatcher();
                m_WatcherWrong.Filter = "*.wrong";
                if (PathToWatch[PathToWatch.Length - 1] != '\\')
                {
                    m_WatcherWrong.Path = PathToWatch + "\\"; // txtFile.Text + "\\";
                }
                else
                {
                    m_WatcherWrong.Path = PathToWatch;
                }

                m_WatcherWrong.IncludeSubdirectories = IncludeSubdirectories;
                m_WatcherWrong.NotifyFilter          = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                                                       | NotifyFilters.FileName | NotifyFilters.DirectoryName;
                m_WatcherWrong.Changed            += new FileSystemEventHandler(OnChanged);
                m_WatcherWrong.Created            += new FileSystemEventHandler(OnCreated);
                m_WatcherWrong.Deleted            += new FileSystemEventHandler(OnDelete);
                m_WatcherWrong.Renamed            += new RenamedEventHandler(OnRenamed);
                m_WatcherWrong.EnableRaisingEvents = true;
                m_bIsWatchingWrong = true;
                return("start watch ok on path, " + PathToWatch + " ,filter: " + "*.wrong");
            }
            catch (Exception err)
            {
                throw (new SystemException(err.Message));
            }
        }
        public bool StopFTPWatcher()
        {
            try
            {
                Thread.Sleep(200);
                //threadReads.Abort();
                if (watcher != null)
                {
                    watcher.EnableRaisingEvents = false;
                    watcher.Created            -= new FileSystemEventHandler(OnCreated);
                    watcher.Dispose();
                    watcher = null;
                    // Form1.log.Info("Watcher Stopped");
                }

                TimerMonitor.Stop();
                TimerPending.Stop();

                TimerMatch.Stop();

                IsRunning = false;
                return(true);
            }
            catch (Exception ex)
            {
                //Form1.log.Error("StopFTPWatcher Error", ex);
                return(false);
            }
        }
示例#19
0
		/// <summary>
		/// 启用重载器
		/// </summary>
		public static void Start() {
			// 指定文件改变时卸载程序域
			Action<string> onFileChanged = (path) => {
				var ext = Path.GetExtension(path).ToLower();
				if (ext == ".cs" || ext == ".json") {
					HttpRuntime.UnloadAppDomain();
				}
			};
			// 绑定文件监视器的事件处理函数并启用监视器
			Action<FileSystemWatcher> startWatcher = (watcher) => {
				watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;
				watcher.Changed += (sender, e) => onFileChanged(e.FullPath);
				watcher.Created += (sender, e) => onFileChanged(e.FullPath);
				watcher.Deleted += (sender, e) => onFileChanged(e.FullPath);
				watcher.Renamed += (sender, e) => { onFileChanged(e.FullPath); onFileChanged(e.OldFullPath); };
				watcher.EnableRaisingEvents = true;
			};
			// 监视插件目录
			var pathManager = Application.Ioc.Resolve<PathManager>();
			pathManager.GetPluginDirectories().Where(p => Directory.Exists(p)).ForEach(p => {
				var pluginFilesWatcher = new FileSystemWatcher();
				pluginFilesWatcher.Path = p;
				pluginFilesWatcher.IncludeSubdirectories = true;
				startWatcher(pluginFilesWatcher);
			});
			// 监视网站配置文件
			var websiteConfigWatcher = new FileSystemWatcher();
			websiteConfigWatcher.Path = PathConfig.AppDataDirectory;
			websiteConfigWatcher.Filter = "*.json";
			startWatcher(websiteConfigWatcher);
		}
示例#20
0
        private void StartFileSystemWatcher()
        {
            if (string.IsNullOrWhiteSpace(SourceFolderPath))
            {
                return;
            }

            var fileSystemWatcher = new System.IO.FileSystemWatcher
            {
                Path         = SourceFolderPath,
                NotifyFilter = NotifyFilters.FileName |
                               NotifyFilters.LastWrite |
                               NotifyFilters.Size |
                               NotifyFilters.DirectoryName,
                IncludeSubdirectories = true,
                EnableRaisingEvents   = true,
            };

            fileSystemWatcher.Created += fileSystemWatcher_CreatedChangedDeleted;
            fileSystemWatcher.Changed += fileSystemWatcher_CreatedChangedDeleted;
            fileSystemWatcher.Deleted += fileSystemWatcher_CreatedChangedDeleted;
            fileSystemWatcher.Renamed += fileSystemWatcher_Renamed;

            WriteLog(string.Format(Properties.Resources.MainWindowsVM_StartFileSystemWatcher_StartFileSystemWatcher, SourceFolderPath));
        }
示例#21
0
 public LogViewer(string spacefilter, List <string> programs, List <string> excludes, AssemblaTicketWindow.LoginSucceedDel loginsuccess, string User, string Pw)
 {
     namefilter   = spacefilter;
     loginsucceed = loginsuccess;
     programlist  = programs;
     exclude      = excludes;
     user         = User;
     pw           = Pw;
     if (loginsucceed == null)
     {
         loginsucceed = new AssemblaTicketWindow.LoginSucceedDel(succeed);
     }
     InitializeComponent();
     if (namefilter != string.Empty)
     {
         Text = PROGRAM + " " + namefilter;
         Invalidate();
     }
     ContextMenu = new ContextMenu();
     ContextMenu.MenuItems.Add("View", new EventHandler(view));
     ContextMenu.MenuItems.Add("Ticket", new EventHandler(aticket));
     ContextMenu.MenuItems.Add("Delete", new EventHandler(del));
     DoubleClick        += new EventHandler(LogViewerMain_DoubleClick);
     _logs.DoubleClick  += new EventHandler(_logs_DoubleClick);
     _logs.SelectionMode = SelectionMode.MultiExtended;
     _logs.Sorted        = true;
     init();
     fsw = new System.IO.FileSystemWatcher(PATH, WILDEXT);
     fsw.IncludeSubdirectories = true;
     fsw.Changed += new System.IO.FileSystemEventHandler(fsw_Changed);
     fsw.Created += new System.IO.FileSystemEventHandler(fsw_Created);
 }
示例#22
0
文件: Form1.cs 项目: RBDLAB/BandWS
        //This method starts to listen to microphone stream
        public void startButton2(object sender, EventArgs e)
        {
            var watch = new System.IO.FileSystemWatcher();

            watch.Path                = ibtPath;
            watch.Filter              = "mic.txt";
            watch.NotifyFilter        = NotifyFilters.LastAccess | NotifyFilters.LastWrite; //more options
            watch.Changed            += new FileSystemEventHandler(OnChanged);
            watch.EnableRaisingEvents = true;

            //determine the singer gender
            if (gender.Text == "Male")
            {
                setGender("Gender=Male;");
            }
            else
            {
                setGender("Gender=Female;");
            }

            minRate = Convert.ToDouble(minRateText.Text);
            maxRate = Convert.ToDouble(maxRateText.Text);

            //min BPM is 81
            //max BPM is 160
            interval = Convert.ToInt32((160 - 81) / (maxRate - minRate));

            //start the IBT process
            using (process = new Process())
            {
                process.StartInfo.UseShellExecute        = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError  = true;
                process.StartInfo.WindowStyle            = ProcessWindowStyle.Minimized;
                process.StartInfo.WorkingDirectory       = @"C:\";
                process.StartInfo.FileName = Path.Combine(Environment.SystemDirectory, "cmd.exe");

                // Redirects the standard input so that commands can be sent to the shell.
                process.StartInfo.RedirectStandardInput = true;
                // Runs the specified command and exits the shell immediately.
                //process.StartInfo.Arguments = @"/c ""dir""";

                process.OutputDataReceived += ProcessOutputDataHandler;
                process.ErrorDataReceived  += ProcessErrorDataHandler;

                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();

                // Send a directory command and an exit command to the shell
                process.StandardInput.WriteLine("cd " + ibtPath);
                process.StandardInput.WriteLine("ibt -mic");
            }

            //change the window title
            Console.WriteLine("Band Without Soloist - Running...");
            BWS.setText("Band Without Soloist - Running...");

            startButton.Enabled = false;
        }
示例#23
0
        public override void Run(IBuildContext context)
        {
            Context = context;
            Context.IsAborted = true;

            var include = context.Configuration.GetString(Constants.Configuration.WatchProjectInclude, "**");
            var exclude = context.Configuration.GetString(Constants.Configuration.WatchProjectExclude, "**");
            _pathMatcher = new PathMatcher(include, exclude);

            _publishDatabase = context.Configuration.GetBool(Constants.Configuration.WatchProjectPublishDatabase, true);

            _fileWatcher = new FileSystemWatcher(context.ProjectDirectory)
            {
                IncludeSubdirectories = true,
                NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName
            };

            _fileWatcher.Changed += FileChanged;
            _fileWatcher.Deleted += FileChanged;
            _fileWatcher.Renamed += FileChanged;
            _fileWatcher.Created += FileChanged;
            _fileWatcher.Created += FileChanged;

            _fileWatcher.EnableRaisingEvents = true;

            Console.WriteLine(Texts.Type__q__to_quit___);

            string input;
            do
            {
                input = Console.ReadLine();
            }
            while (!string.Equals(input, "q", StringComparison.OrdinalIgnoreCase));
        }
示例#24
0
        private void StartFileSystemWatcher()
        {
            string folderPath = this.TextBoxFolderPath.Text;

            // If there is no folder selected, to nothing
            if (string.IsNullOrWhiteSpace(folderPath) || !System.IO.Directory.Exists(folderPath))
            {
                return;
            }

            System.IO.FileSystemWatcher fileSystemWatcher = new System.IO.FileSystemWatcher();

            // Set folder path to watch
            fileSystemWatcher.Path = folderPath;

            // Gets or sets the type of changes to watch for.
            // In this case we will watch change of filename, last modified time, size and directory name
            fileSystemWatcher.NotifyFilter = System.IO.NotifyFilters.FileName |
                                             System.IO.NotifyFilters.LastWrite |
                                             System.IO.NotifyFilters.Size |
                                             System.IO.NotifyFilters.DirectoryName;


            // Event handlers that are watching for specific event
            fileSystemWatcher.Created += new System.IO.FileSystemEventHandler(fileSystemWatcher_Created);
            //fileSystemWatcher.Changed += new System.IO.FileSystemEventHandler(fileSystemWatcher_Changed);
            fileSystemWatcher.Deleted += new System.IO.FileSystemEventHandler(fileSystemWatcher_Deleted);
            //fileSystemWatcher.Renamed += new System.IO.RenamedEventHandler(fileSystemWatcher_Renamed);

            // NOTE: If you want to monitor specified files in folder, you can use this filter
            // fileSystemWatcher.Filter

            // START watching
            fileSystemWatcher.EnableRaisingEvents = true;
        }
示例#25
0
        private void StartWatch_Click(object sender, EventArgs e)
        {
            var sourceButton = ((Button)sender).Name;
            DialogResult selectedFolder = fbdWatch.ShowDialog();
            if (selectedFolder != DialogResult.OK) return;

            this.Watcher = new FileSystemWatcher();
            this.Watcher.Path = fbdWatch.SelectedPath;
            if (sourceButton == "bPluginStartWatch")
            {
                this.Watcher.Filter = "*.dll";
                lblPluginWatch.Text = $"Watching {fbdWatch.SelectedPath}";
                bPluginStopWatch.Enabled = true;
                tbLogPlugin.Text = "";
            }
            else if (sourceButton == "bJavascriptStartWatch")
            {
                this.Watcher.Filter = "*.js";
                lblJavascriptWatch.Text = $"Watching {fbdWatch.SelectedPath}";
                bJavascriptStopWatch.Enabled = true;
                tbLogJavascript.Text = "";
            }
            this.Watcher.IncludeSubdirectories = true;
            this.Watcher.NotifyFilter = NotifyFilters.LastWrite;
            this.Watcher.EnableRaisingEvents = true;

            this.Watcher.Changed -= Watcher_OnChanged;
            this.Watcher.Changed += Watcher_OnChanged;
        }
 private void InitWatchers()
 {
     System.IO.FileSystemWatcher watcher = null;
     System.String[]             paths   = System.Configuration.ConfigurationManager.AppSettings["folderPath"].Split(';');
     System.String[]             filters = System.Configuration.ConfigurationManager.AppSettings["fileFilter"].Split(';');
     //System.Console.WriteLine(paths);
     //System.Console.WriteLine(filters);
     this.watchers = new System.Collections.Generic.List <System.IO.FileSystemWatcher>();
     foreach (System.String path in paths)
     {
         if (path == "")
         {
             continue;
         }
         foreach (System.String filter in filters)
         {
             watcher = new System.IO.FileSystemWatcher();
             ((System.ComponentModel.ISupportInitialize)(watcher)).BeginInit();
             watcher.Path                  = path;
             watcher.Filter                = filter;
             watcher.NotifyFilter          = ((System.IO.NotifyFilters)((System.IO.NotifyFilters.FileName | System.IO.NotifyFilters.Size | System.IO.NotifyFilters.DirectoryName)));
             watcher.Changed              += new System.IO.FileSystemEventHandler(this.watcherChanged);
             watcher.Created              += new System.IO.FileSystemEventHandler(this.watcherCreated);
             watcher.Deleted              += new System.IO.FileSystemEventHandler(this.watcherDeleted);
             watcher.Renamed              += new System.IO.RenamedEventHandler(this.watcherRenamed);
             watcher.EnableRaisingEvents   = true;
             watcher.IncludeSubdirectories = (System.Configuration.ConfigurationManager.AppSettings["includeSubDirs"] == "true") ? true : false;
             ((System.ComponentModel.ISupportInitialize)(watcher)).EndInit();
             this.watchers.Add(watcher);
         }
     }
 }
示例#27
0
 internal void StartWatch()
 {
     m_FileWatcher = new FileSystemWatcher();
     m_FileWatcher.Path =this.sourceFolder;
     m_FileWatcher.Created += new FileSystemEventHandler(FileWatcher_Created);
     m_FileWatcher.EnableRaisingEvents = true;
 }
示例#28
0
 private static void MonitorFolder(string folderFullPath)
 {
     System.IO.FileSystemWatcher watcher = new System.IO.FileSystemWatcher(folderFullPath, "*.csv");
     watcher.EnableRaisingEvents = true;
     watcher.NotifyFilter        = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite;
     watcher.Created            += new FileSystemEventHandler(OnChanged);
 }
示例#29
0
 public FileWatcher(bool initDirvers, bool subDirector, bool throwException)
 {
     try
     {
         if (initDirvers)
         {
             foreach (DriveInfo di in DriveInfo.GetDrives())
             {
                 try
                 {
                     FileSystemWatcher fsw = new FileSystemWatcher();
                     fsw.Path = di.Name;
                     fsw.IncludeSubdirectories = subDirector;
                     fsw.Changed += new FileSystemEventHandler(fsw_Changed);
                     fsw.Created += new FileSystemEventHandler(fsw_Created);
                     fsw.Deleted += new FileSystemEventHandler(fsw_Deleted);
                     fsw.Renamed += new RenamedEventHandler(fsw_Renamed);
                     _watcherArr.Add(fsw);
                 }
                 catch { if (throwException) throw new Exception(di.Name + "�̷���ʧ�ܣ�"); }
             }
         }
     }
     catch (Exception e) { MessageBox.Show(e.Message); MessageBox.Show(e.ToString()); }
 }
示例#30
0
    /// <summary>Fileモード用のファイルの監視の属性。
    /// 秀丸がファイル名を変更したり、ディレクトリを変更したりしても追跡できるようにするため。
    /// 又、ファイルの保存時は、webBrowserの内容を更新する。
    /// </summary>
    protected void SetWatcherAttribute()
    {
        try
        {
            if (strCurFileFullPath.Length > 0)
            {
                if (watcher == null)
                {
                    watcher = new System.IO.FileSystemWatcher();
                    watcher.NotifyFilter = (System.IO.NotifyFilters.LastAccess | System.IO.NotifyFilters.LastWrite | System.IO.NotifyFilters.FileName | System.IO.NotifyFilters.DirectoryName);
                }
                watcher.Path = System.IO.Path.GetDirectoryName(strCurFileFullPath);
                // wbとは内容更新が非同期衝突するので、そこは同期せよ
                watcher.SynchronizingObject = wb;
                watcher.Filter = "*.*";

                watcher.Changed += new FileSystemEventHandler(watcher_Changed);
                watcher.IncludeSubdirectories = false;

                //監視を開始する
                watcher.EnableRaisingEvents = true;
            }
        }
        catch (Exception)
        {
        }
    }
示例#31
0
            /// <summary>
            /// Creates the fit function service. Starts a thread that will walk through all items in the fit function directory.
            /// </summary>
            /// <param name="fitFunctionDirectory">Directory where the fit functions reside.</param>
            /// <param name="isReadOnly">If true, only read access to that directory is allowed.</param>
            public FileBasedFitFunctionService(string fitFunctionDirectory, bool isReadOnly)
            {
                _userDefinedFunctions = new SortedList <string, FileBasedFitFunctionInformation>();
                _filesToProcess       = new Queue <string>();
                _fitFunctionDirectory = fitFunctionDirectory;

                if (!Directory.Exists(_fitFunctionDirectory) && !isReadOnly)
                {
                    System.IO.Directory.CreateDirectory(_fitFunctionDirectory);
                }

                if (Directory.Exists(_fitFunctionDirectory))
                {
                    _fitFunctionDirectoryWatcher = new FileSystemWatcher(_fitFunctionDirectory, "*,xml");

                    _fitFunctionDirectoryWatcher.Changed += new FileSystemEventHandler(EhChanged);
                    _fitFunctionDirectoryWatcher.Created += new FileSystemEventHandler(EhChanged);
                    _fitFunctionDirectoryWatcher.Deleted += new FileSystemEventHandler(EhDeleted);
                    _fitFunctionDirectoryWatcher.Renamed += new RenamedEventHandler(EhRenamed);

                    // Begin watching.
                    _fitFunctionDirectoryWatcher.EnableRaisingEvents = true;

                    // for the first, enqueue all files in this directory for processing
                    string[] names = Directory.GetFiles(_fitFunctionDirectory, "*.xml", SearchOption.TopDirectoryOnly);
                    foreach (string name in names)
                    {
                        _filesToProcess.Enqueue(name);
                    }

                    // Start the thread
                    _threadIsWorking = true;
                    System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(this.ProcessFiles));
                }
            }
示例#32
0
文件: FrmMain.cs 项目: imatary/work
        private void Btn_AutoRun_Click(object sender, EventArgs e)
        {
            if (v_IsWatching)
            {
                v_IsWatching = false;
                fileSystemWatcherLogs.EnableRaisingEvents = false;
                fileSystemWatcherLogs.Dispose();
                Btn_AutoRun.BackColor = Color.Blue;
                Btn_AutoRun.Text      = "Start Scan";
            }
            else
            {
                v_IsWatching          = true;
                Btn_AutoRun.BackColor = Color.Red;
                Btn_AutoRun.Text      = "Stop Scan";
                fileSystemWatcherLogs = new System.IO.FileSystemWatcher();
                string v_FolderInput = ConfigurationManager.AppSettings["PathInput"].ToString();
                fileSystemWatcherLogs.Filter = "*.*";
                fileSystemWatcherLogs.Path   = v_FolderInput + "\\";


                fileSystemWatcherLogs.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                                                     | NotifyFilters.FileName | NotifyFilters.DirectoryName;
                fileSystemWatcherLogs.Changed += new FileSystemEventHandler(OnChanged);
                //fileSystemWatcherLogs.Created += new FileSystemEventHandler(OnChanged);
                //fileSystemWatcherLogs.Deleted += new FileSystemEventHandler(OnChanged);
                //fileSystemWatcherLogs.Renamed += new RenamedEventHandler(OnRenamed);
                fileSystemWatcherLogs.EnableRaisingEvents = true;
            }
        }
示例#33
0
        public SingleFileWatcher(ToolStrip ui, string path, SingleFileWathcerChangedHandler callback)
        {
            singleFileWathcerChangedHandler = callback;

            delex = new DelayExecuter(1000, delegate() { singleFileWathcerChangedHandler(); });

            watcher = new System.IO.FileSystemWatcher();
            //監視するディレクトリを指定
            watcher.Path = Path.GetDirectoryName(path);
            //監視するファイルを指定
            watcher.Filter = Path.GetFileName(path);
            //最終更新日時、ファイルサイズの変更を監視する
            watcher.NotifyFilter =
                (System.IO.NotifyFilters.Size
                |System.IO.NotifyFilters.LastWrite);
            //UIのスレッドにマーシャリングする
            watcher.SynchronizingObject = ui;

            //イベントハンドラの追加
            watcher.Changed += new System.IO.FileSystemEventHandler(watcherChanged);
            watcher.Created += new System.IO.FileSystemEventHandler(watcherChanged);

            //監視を開始する
            watcher.EnableRaisingEvents = true;
        }
示例#34
0
        public FileViewer()
        {
            Label             = Icons.PanelFileViewer + Resources.GetString("FileViewer") + "###FileVeiwer";
            Core.OnAfterLoad += OnAfterLoad;
            Core.OnAfterNew  += OnAfterLoad;
            Core.OnAfterSave += OnAfterSave;

            UpdateFileListWithProjectPath(Core.Root.GetFullPath());

            TabToolTip = Resources.GetString("FileViewer");

            menuOpenFile = Resources.GetString("FileViewer_OpenFile");

            if (swig.GUIManager.IsMacOSX())
            {
                menuShowInFileManager = Resources.GetString("FileViewer_ShowInFinder");
            }
            else
            {
                menuShowInFileManager = Resources.GetString("FileViewer_ShowInExplorer");
            }
            menuImportFromPackage = Resources.GetString("FileViewer_ImportFromPackage");
            menuExportToPackage   = Resources.GetString("FileViewer_ExportToPackage");

            directoryWatcher          = new FileSystemWatcher();
            directoryWatcher.Changed += (o, e) => { shouldUpdateFileList = true; };
            directoryWatcher.Renamed += (o, e) => { shouldUpdateFileList = true; };
            directoryWatcher.Deleted += (o, e) => { shouldUpdateFileList = true; };
            directoryWatcher.Created += (o, e) => { shouldUpdateFileList = true; };

            UpdateFileList(Directory.GetCurrentDirectory());
        }
示例#35
0
        public FileWatcher(string path, string[] filter)
        {
            if (filter == null || filter.Length == 0)
            {
                FileSystemWatcher mWather = new FileSystemWatcher(path);
                mWather.Changed += new FileSystemEventHandler(fileSystemWatcher_Changed);
                mWather.Deleted += new FileSystemEventHandler(fileSystemWatcher_Changed);
                mWather.Created += new FileSystemEventHandler(fileSystemWatcher_Changed);
                mWather.EnableRaisingEvents = true;
                mWather.IncludeSubdirectories = false;
                mWathers.Add(mWather);
            }
            else
            {
                foreach (string item in filter)
                {
                    FileSystemWatcher mWather = new FileSystemWatcher(path, item);
                    mWather.Changed += new FileSystemEventHandler(fileSystemWatcher_Changed);
                    mWather.Deleted += new FileSystemEventHandler(fileSystemWatcher_Changed);
                    mWather.Created += new FileSystemEventHandler(fileSystemWatcher_Changed);
                    mWather.EnableRaisingEvents = true;
                    mWather.IncludeSubdirectories = false;
                    mWathers.Add(mWather);
                }
            }
            mTimer = new System.Threading.Timer(OnDetect, null, 5000, 5000);

        }
        public static void StartFileWatcher(IOptionsMonitor <LiveReloadConfiguration> config)
        {
            // If this is a first start, initialize the config monitoring
            if (Config is null)
            {
                Config = config;
                Config.OnChange(OnConfigChanged);
            }

            if (!Config.CurrentValue.LiveReloadEnabled)
            {
                return;
            }

            var path = Config.CurrentValue.FolderToMonitor;

            path = Path.GetFullPath(path);

            Watcher        = new FileSystemWatcher(path);
            Watcher.Filter = "*.*";
            Watcher.EnableRaisingEvents   = true;
            Watcher.IncludeSubdirectories = true;

            Watcher.NotifyFilter = NotifyFilters.LastWrite
                                   | NotifyFilters.FileName
                                   | NotifyFilters.DirectoryName;



            Watcher.Changed += Watcher_Changed;
            Watcher.Created += Watcher_Changed;
            Watcher.Renamed += Watcher_Renamed;
        }
示例#37
0
        static void Main(string[] args)
        {
            FileSystemWatcher watcher = new FileSystemWatcher();
            try
            {
                watcher.Path = @"C:\_test\photos\";
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }

            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            watcher.Filter = "*.txt";
            watcher.Created += (source, e) => Console.WriteLine("{0} -- {1}", e.FullPath, e.ChangeType);
            watcher.Changed += (source, e) => Console.WriteLine("{0} -- {1}", e.FullPath, e.ChangeType);
            watcher.Deleted += (source, e) => Console.WriteLine("{0} -- {1}", e.FullPath, e.ChangeType);
            watcher.Renamed += (source, e) => Console.WriteLine("{0} -- {1}", e.FullPath, e.ChangeType);
            // Begin watching the directory.
            watcher.EnableRaisingEvents = true;

            ReadAndWrite();

            // Wait for the user to quit the program.
            Console.WriteLine(@"Press 'q' to quit app.");
            while (Console.Read() != 'q')
                ;
        }
示例#38
0
文件: FormMods.cs 项目: aphadeon/BotM
        public FormMods()
        {
            InitializeComponent();
            CenterToScreen();
            listBoxInstalled.DataSource    = new BindingList <ModListing>();
            listBoxNotInstalled.DataSource = new BindingList <ModListing>();
            UpdateModList();

            var feh  = new System.IO.FileSystemEventHandler(OnFileEvent);
            var feh2 = new System.IO.RenamedEventHandler(OnFileEvent);

            System.IO.FileSystemWatcher watcher1 = new System.IO.FileSystemWatcher
            {
                Path         = MainForm.Settings.NotInstalledModsDirectory,
                NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName,
                Filter       = "*.botm.zip"
            };
            watcher1.Created            += feh;
            watcher1.Changed            += feh;
            watcher1.Renamed            += feh2;
            watcher1.Deleted            += feh;
            watcher1.EnableRaisingEvents = true;
            System.IO.FileSystemWatcher watcher2 = new System.IO.FileSystemWatcher
            {
                Path         = MainForm.Settings.NotInstalledModsDirectory,
                NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName,
                Filter       = "*.botm.zip"
            };
            watcher2.Created            += feh;
            watcher2.Deleted            += feh;
            watcher2.EnableRaisingEvents = true;
        }
示例#39
0
       /// <summary>
       /// Initializes the <see cref="ViewManager"/> class.
       /// </summary>
       static ViewManager()
       {
           if (_viewCache == null)
           {
               lock (_key)
               {
                   if (_viewCache == null)
                   {
                       _viewCache = new Dictionary<string, CachedView>();
                   }
               }
           }
           if (_fileSystemWatcher == null)
           {
               lock (_fileWatcherKey)
               {
                   if (_fileSystemWatcher == null)
                   {
                       try
                       {
                           _fileSystemWatcher = new FileSystemWatcher(HttpRuntime.AppDomainAppPath, "*.cshtml");
                           _fileSystemWatcher.Changed += new FileSystemEventHandler(OnChanged);
                           _fileSystemWatcher.EnableRaisingEvents = true;
                           _fileSystemWatcher.IncludeSubdirectories = true;
                       }
                       catch (Exception ex)
                       {
                           Sitecore.Diagnostics.Log.Error("Failed to setup Razor file watcher.", ex);
                       }
                   }
               }
           }
 
       }
示例#40
0
        public static void Main()
        {
            //Demonstrates the FileSystemWatcher class
            System.IO.FileSystemWatcher fileWatcher = new System.IO.FileSystemWatcher();
            fileWatcher.Path = @"..\..\BaseClassLibrary\FileSystemWatcher\WatchFolder";
            // Check changes in LastAccess/LastWrite times
            // Check for renaming of directories/files.
            fileWatcher.NotifyFilter = (System.IO.NotifyFilters.LastAccess |
                                        System.IO.NotifyFilters.LastWrite |
                                        System.IO.NotifyFilters.FileName |
                                        System.IO.NotifyFilters.DirectoryName);
            // determine which files to watch for
            fileWatcher.Filter = "*.xml";

            // Add event handlers for change events.
            fileWatcher.Changed += new FileSystemEventHandler(fileWatcher_Change);
            fileWatcher.Created += new FileSystemEventHandler(fileWatcher_Change);
            fileWatcher.Deleted += new FileSystemEventHandler(fileWatcher_Change);

            // Start watching...this must be set to true
            fileWatcher.EnableRaisingEvents = true;
            Console.WriteLine("Watching for changes....");

            Console.ReadLine();
        }
        public PythonInterpreterFactoryWithDatabase(
            Guid id,
            string description,
            InterpreterConfiguration config,
            bool watchLibraryForChanges
        ) {
            _description = description;
            _id = id;
            _config = config;

            if (watchLibraryForChanges && Directory.Exists(_config.LibraryPath)) {
                _refreshIsCurrentTrigger = new Timer(RefreshIsCurrentTimer_Elapsed);

                _libWatcher = CreateLibraryWatcher();

                _isCheckingDatabase = true;
                _refreshIsCurrentTrigger.Change(1000, Timeout.Infinite);

                _verWatcher = CreateDatabaseVerWatcher();
                _verDirWatcher = CreateDatabaseDirectoryWatcher();
            }

            // Assume the database is valid if the directory exists, then switch
            // to invalid after we've checked.
            _isValid = Directory.Exists(DatabasePath);
        }
示例#42
0
 public void StopWatch()
 {
     try
     {
         if (m_Watcher != null)
         {
             m_bIsWatching = false;
             m_event.Set();
             m_Watcher.EnableRaisingEvents = false;
             m_Watcher.Dispose();
             m_Watcher = null;
             while (m_queue.Count > 0)
             {
                 UploadFileToServerWithPath(m_queue.Dequeue());
             }
             if (m_dropboxInitialized == true)
             {
                 m_dropbox.Close();
                 m_dropboxInitialized = false;
             }
         }
     }
     catch (Exception err)
     {
         throw (new SystemException(err.Message));
     }
 }
示例#43
0
        private void StartFileWatcher()
        {
            string methodName = MethodBase.GetCurrentMethod().Name;
            logger.InfoFormat("BEGIN: {0}()", methodName);
            try
            {
                var configurationFileDirectory = new FileInfo(Configuration.FilePath).Directory;
                string fileName = Path.GetFileName(Configuration.FilePath);

                logger.InfoFormat("Monitor Configuration path:{0} file:{1}", configurationFileDirectory.FullName, fileName);
                _fileWatcher = new FileSystemWatcher(configurationFileDirectory.FullName);
                _fileWatcher.Filter = fileName;
                _fileWatcher.NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastWrite;
                _fileWatcher.Changed += ConfigFileWatcherOnChanged;
                _fileWatcher.EnableRaisingEvents = true;
            }
            catch (Exception e)
            {
                logger.Error(methodName, e);
            }
            finally
            {
                logger.InfoFormat("END: {0}()", methodName);
            }
        }
示例#44
0
        /// <summary>
        /// Sets the file watchers for the local directory.
        /// </summary>
        public void Setup()
        {
            Log.Write(l.Debug, "Setting the file system watchers");

            _fswFiles = new FileSystemWatcher();
            _fswFolders = new FileSystemWatcher();
            _fswFiles.Path = controller.Paths.Local;
            _fswFolders.Path = controller.Paths.Local;
            _fswFiles.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
            _fswFolders.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.DirectoryName;

            _fswFiles.Filter = "*";
            _fswFolders.Filter = "*";

            _fswFiles.IncludeSubdirectories = true;
            _fswFolders.IncludeSubdirectories = true;

            // add event handlers for files:
            _fswFiles.Changed += FileChanged;
            _fswFiles.Created += FileChanged;
            _fswFiles.Deleted += OnDeleted;
            _fswFiles.Renamed += OnRenamed;
            // and for folders:
            //fswFolders.Changed += new FileSystemEventHandler(FolderChanged);
            _fswFolders.Created += FolderChanged;
            _fswFolders.Deleted += OnDeleted;
            _fswFolders.Renamed += OnRenamed;

            _fswFiles.EnableRaisingEvents = true;
            _fswFolders.EnableRaisingEvents = true;

            Log.Write(l.Debug, "File system watchers setup completed!");
        }
示例#45
0
        private void WatchChange()
        {
            if (string.IsNullOrEmpty(settings.ScanBasePath))
            {
                log.LogError("Scan path is empty. Cannot start watching folder change.");
                return;
            }

            try
            {
                var changeWatcher = new System.IO.FileSystemWatcher();
                changeWatcher.Path = settings.ScanBasePath;
                changeWatcher.IncludeSubdirectories = true;
                changeWatcher.Filter              = "*.jpg";
                changeWatcher.Created            += ChangeHandler;
                changeWatcher.EnableRaisingEvents = true;
                log.LogInfo(string.Format("Start watching change in folder {0}", settings.ScanBasePath));
            }
            catch (ArgumentException ae)
            {
                string msg = string.Format("Watching folder {0} is not valid, please indicate a valid folder and restart application", settings.ScanBasePath);
                log.LogError(msg);
                msgDispatcher.PopulateMessage(msg);
            }
            catch (Exception e)
            {
                log.LogException("Start watching change exception. ", e);
            }
        }
示例#46
0
        public TemplateFile(string templatePath, TransformationData data)
        {
            this.nonDynamicHTMLOutput = data.NonDynamicHTMLOutput;
            this.publishFlags = data.Markdown.PublishFlags;
            ParsedTemplate = null;

            if (string.IsNullOrWhiteSpace(templatePath))
            {
                throw new System.ArgumentException("Template path should be valid path.");
            }

            ReparseTemplate(templatePath);

            var templatePathDir = Path.GetDirectoryName(templatePath);
            var templatePathFileName = Path.GetFileName(templatePath);

            if (templatePathDir != null && templatePathFileName != null)
            {
                fileWatcher = new FileSystemWatcher(templatePathDir, templatePathFileName)
                    {
                        EnableRaisingEvents = true
                    };

                fileWatcher.Changed += (sender, args) =>
                    {
                        ReparseTemplate(templatePath);
                        if (TemplateChanged != null)
                        {
                            TemplateChanged();
                        }
                    };
            }
        }
示例#47
0
        public MainWindowViewModel()
        {
            _searchText                   = string.Empty;
            _hostsFilePath                = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), @"drivers\etc");
            _hostsFileName                = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), @"drivers\etc\hosts");
            _hostItems                    = new ObservableCollection <HostItem>();
            _filteredHostItems            = new ObservableCollection <HostItem>();
            _hostItems.CollectionChanged += _hostItems_CollectionChanged;
            _targets = new ObservableCollection <TargetAddress>();

            Browsers = BrowserHelper.GetInstalledBrowsers();


            SelectedHostItemBindingChanged = new SelectedHostItemBindingChangedCommand(this);
            ClearSelectedTargetTag         = new ClearSelectedTargetTagCommand(this);
            LaunchBrowser = new LaunchBrowserCommand(this);

            LoadHostsFile();
            ParseHostFileContents();

            PropertyChanged += MainWindowViewModel_PropertyChanged;

            _hostsWatcher                     = new FileSystemWatcher();
            _hostsWatcher.Path                = _hostsFilePath;
            _hostsWatcher.NotifyFilter        = NotifyFilters.LastWrite;
            _hostsWatcher.Changed            += _hostsWatcher_Changed;
            _hostsWatcher.EnableRaisingEvents = true;
        }
示例#48
0
文件: Watcher.cs 项目: nikkw/W2C
 public static void Init()
 {
     watcher = new FileSystemWatcher(Folder.GetWatcherPath());
     watcher.IncludeSubdirectories = false;
     watcher.Created += new FileSystemEventHandler(OnCreate);
     watcher.EnableRaisingEvents = true;
 }
示例#49
0
 // ************************************************
 // Class constructor
 public XmlHotDocument()
     : base()
 {
     m_watcher = new FileSystemWatcher();
     HasChanges = false;
     EnableFileChanges = false;
 }
示例#50
0
文件: DummyDoc.cs 项目: beZong/bZmd
        public DummyDoc()
        {
            InitializeComponent();

			Global.myDebug("after InitializeComponent()");

			#region MarkdownWin
			// MarkdownWin *21
			browser.DocumentCompleted += browser_DocumentCompleted;
			// browser.PreviewKeyDown += browser_PreviewKeyDown;
			browser.AllowWebBrowserDrop = false;
			// browser.IsWebBrowserContextMenuEnabled = false;		// ContextMenu Enabled
			//browser.WebBrowserShortcutsEnabled = false;			// Shortcuts Enabled
			//browser.AllowNavigation = false;
			browser.ScriptErrorsSuppressed = true;

			browser.StatusTextChanged += browser_StatusTextChange; // new DWebBrowserEvents2_StatusTextChangeEventHandler(AxWebBrowser_StatusTextChange)

			_fileWatcher = new FileSystemWatcher();		// need assign in Class constructor
			_fileWatcher.NotifyFilter = NotifyFilters.Size |  NotifyFilters.LastWrite;
			_fileWatcher.Changed += new FileSystemEventHandler(OnWatchedFileChanged);
			bgRefreshWorker.RunWorkerAsync();

			this.Disposed += new EventHandler(Watcher_Disposed);
			browser.AllowWebBrowserDrop = false;

			#endregion
		}
        public void StartListening(string directory, string filter, Func<string, Task> updated)
        {
            _fileSystemWatcher?.Dispose();

            _fileSystemWatcher = new FileSystemWatcher(directory, filter)
            {
                EnableRaisingEvents = true,
                IncludeSubdirectories = true
            };

            _fileSystemWatcher.Created += async (sender, eventArgs) =>
            {
                await updated(eventArgs.FullPath).ConfigureAwait(false);
            };

            _fileSystemWatcher.Changed += async (sender, eventArgs) =>
            {
                await updated(eventArgs.FullPath).ConfigureAwait(false);
            };

            _fileSystemWatcher.Deleted += async (sender, eventArgs) =>
            {
                await updated(eventArgs.FullPath).ConfigureAwait(false);
            };

            _fileSystemWatcher.Renamed += async (sender, eventArgs) =>
            {
                await updated(eventArgs.FullPath).ConfigureAwait(false);
            };
        }
示例#52
0
		public override void Close ()
		{
			if (file_watcher != null) {
				file_watcher.EnableRaisingEvents = false;
				file_watcher = null; // force creation of new FileSystemWatcher
			}
		}
示例#53
0
        static void SetupFileSynchronization()
        {
            FileSystemEventHandler onFileCreatedOrChanged = (object sender, FileSystemEventArgs e) =>
            {
                var blob = _container.GetBlockBlobReference(e.Name);
                Console.WriteLine("Uploading '{0}'", e.Name);
                blob.UploadFromFileAsync(e.FullPath, FileMode.Open);
            };

            FileSystemEventHandler onFileDeleted = (object sender, FileSystemEventArgs e) =>
            {
                var blob = _container.GetBlockBlobReference(e.Name);
                Console.WriteLine("Deleting '{0}'", e.Name);
                blob.DeleteIfExists();
            };

            var watcher = new System.IO.FileSystemWatcher(_path);

            watcher.Created            += onFileCreatedOrChanged;
            watcher.Changed            += onFileCreatedOrChanged;
            watcher.Deleted            += onFileDeleted;
            watcher.EnableRaisingEvents = true;

            Console.WriteLine("Watching {0}!", _path);
        }
示例#54
0
文件: Form1.cs 项目: 305088020/-SVN
        public Form1()
        {
            InitializeComponent();
            //初始化得到配置文件中的SVN内网外网CheckOut地址
            string SVN_W = AppSettings.GetValue("SVN_W");
            string SVN_N = AppSettings.GetValue("SVN_N");
            string SVN_TIME = AppSettings.GetValue("SVN_TIME");
            string SlEEP_TIME = AppSettings.GetValue("SlEEP_TIME");

            textBox1.Text = SVN_W;
            textBox2.Text = SVN_N;
            textBox3.Text = SlEEP_TIME;
            textBox4.Text = SVN_TIME;
            //定时器打开
            InitalizeTimer();
            //监视外网文件
            this.watcher_W = new FileSystemWatcher();
            this.watcher_W.Deleted += new FileSystemEventHandler(watcher_Deleted);
            this.watcher_W.Renamed += new RenamedEventHandler(watcher_Renamed);
            this.watcher_W.Changed += new FileSystemEventHandler(watcher_Changed);
            this.watcher_W.Created += new FileSystemEventHandler(watcher_Created);
            //监视内网仓库
            this.watcher_N = new FileSystemWatcher();
            this.watcher_N.Deleted += new FileSystemEventHandler(watcher_Deleted_N);
            this.watcher_N.Renamed += new RenamedEventHandler(watcher_Renamed_N);
            this.watcher_N.Changed += new FileSystemEventHandler(watcher_Changed_N);
            this.watcher_N.Created += new FileSystemEventHandler(watcher_Created_N);
        }
示例#55
0
        public static int Main(string[] args)
        {
            List<string> pargs = ndclTools.ParamForm(args);
            if (pargs.FindParam("-h") || pargs.FindParam("--help"))
            {
                outputHelp();
                return 0;
            }
            int timeout;
            if (!getTimeout(pargs, out timeout))
                return 1;

            watch = new FileSystemWatcher();
            if(!getPath(pargs, watch))
                return 1;

            if (pargs.FindParam("-d"))
                watch.Deleted += new FileSystemEventHandler(handler);
            if (!pargs.FindParam("-c"))
                watch.Changed += new FileSystemEventHandler(handler);
            if (!pargs.FindParam("-C"))
                watch.Created += new FileSystemEventHandler(handler);
            if (!pargs.FindParam("-r"))
                watch.Renamed += new RenamedEventHandler(handler);
            watch.IncludeSubdirectories = pargs.FindParam("-s");

            last = new Tuple<string, DateTime>("", DateTime.Now);

            watch.EnableRaisingEvents = true;
            if (timeout == -1)
                while (Console.Read() != 'q') ;
            else
                System.Threading.Thread.Sleep(timeout);
            return 0;
        }
示例#56
0
        public FileWatcher(string path, string filer, string outFile)
        {
            var a = new System.IO.FileSystemWatcher(path, filer)
            {
                IncludeSubdirectories = true,
                EnableRaisingEvents = true
            };
            OutFile = outFile;
            Path = path;
            Filter = filer;
            FileModels = new List<FileModel>();
            a.Changed += async (sender, e) =>
            {
                var sw = new Stopwatch();
                sw.Start();
                if (isIn)
                    return;
                lock (this)
                {
                    if (isIn)
                        return;
                    isIn = true;
                }
                if ((e is FileSystemEventArgs ee))
                {
                    FileModels.Clear();
                    await UpdateFiles();
                    //var TsProj = new DataAtr.Models.Typescript.TypeDeffinition(new DataAtr.Models.ProjectModel { FileModels = FileModels }).TypescriptPoject();
                    //File.WriteAllText(outFile, TsProj);
                    //Console.WriteLine($"{DateTime.Now.ToLongTimeString()}: Update ({sw.ElapsedMilliseconds}ms) {(isIn ? "" : "false")}");
                    isIn = false;
                }
            };

        }
示例#57
0
        public MainWindow()
        {
            InitializeComponent();
            ConnectionsListView.ItemsSource = _storageAccountConnections;
            IDeploymentRepositoryFactory deploymentRepositoryFactory = new DeploymentRepositoryFactory();
            _deploymentRepositoryManager = new DeploymentRepositoryManager(deploymentRepositoryFactory);
            _jsonSerializer = new JsonSerializer(new DiagnosticsTraceWriter());
            _deploymentConfigSerializer = new JsonDeploymentConfigSerializer(_jsonSerializer);
            if (File.Exists(SettingsFilePath))
            {
                string json = File.ReadAllText(SettingsFilePath);
                _storageAccountConnections = _jsonSerializer.Deserialize<List<StorageAccountConnectionInfo>>(json);
                ConnectionsListView.ItemsSource = _storageAccountConnections;
            }

            if (!Directory.Exists(DeploymentsConfigsDirPath))
            {
                Directory.CreateDirectory(DeploymentsConfigsDirPath);
            }

	        _deploymentConfigFileWatcher = new FileSystemWatcher
	        {
		        Path = Path.GetFullPath(DeploymentsConfigsDirPath),
		        NotifyFilter = NotifyFilters.LastWrite,
		        Filter = "*.json"
	        };
	        _deploymentConfigFileWatcher.Changed += OnDeploymentConfigFileChanged;
            _deploymentConfigFileWatcher.EnableRaisingEvents = true;
        }
示例#58
0
        private static void Run()
        {
            try
            {
                // Check is valid directory
                if(string.IsNullOrEmpty(BaseConfig.Watcher.Path) && !Directory.Exists(BaseConfig.Watcher.Path))
                {
                    Console.WriteLine("Invalid directory. Please check configuration.");
                    return;
                }

                // Create watcher
                FileSystemWatcher watcher = new FileSystemWatcher()
                {
                    Path = BaseConfig.Watcher.Path,
                    NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName,
                    Filter = BaseConfig.Watcher.Filter,
                    EnableRaisingEvents = true,
                };

                // Add event handlers.
                watcher.Changed += new FileSystemEventHandler(OnChanged);
                watcher.Created += new FileSystemEventHandler(OnChanged);
                watcher.Deleted += new FileSystemEventHandler(OnChanged);
                watcher.Renamed += new RenamedEventHandler(OnRenamed);

                // Wait for the user to quit the program.
                Console.WriteLine("Press \'q\' to quit the sample.");
                while (Console.Read() != 'q') ;
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
示例#59
0
        private void Run()
        {
            // Create a new FileSystemWatcher and set its properties.
            watcher = new FileSystemWatcher();

            try
            { 
                watcher.Path = path;

                /* Watch for changes in LastAccess and LastWrite times, and
                   the renaming of files or directories. */
                watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                   | NotifyFilters.FileName | NotifyFilters.DirectoryName;
                // Watch all files
                watcher.Filter = "*.*";

                // Add event handlers.
                watcher.Changed += new FileSystemEventHandler(OnChanged);
                watcher.Created += new FileSystemEventHandler(OnCreated);
                watcher.Deleted += new FileSystemEventHandler(OnDeleted);
                watcher.Renamed += new RenamedEventHandler(OnRenamed);
                //set to watch subfolders
                watcher.IncludeSubdirectories = true;
                // Begin watching.
                watcher.EnableRaisingEvents = true;

            }
            catch (SystemException) 
            { 
              //wrong folder
                return;
            }
        }
示例#60
0
        /// <summary>
        /// 返回ConfigReader 对象(单件模式)
        /// </summary>
        /// <returns></returns>
        private static ConfigReader Create()
        {
            if (_ConfigReader != null)
            {
                return(_ConfigReader);
            }
            if (watcher == null)
            {
                watcher                       = new System.IO.FileSystemWatcher();
                watcher.Path                  = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config");
                watcher.Filter                = "*.config";
                watcher.Changed              += new System.IO.FileSystemEventHandler(watcher_Changed);
                watcher.EnableRaisingEvents   = true;
                watcher.IncludeSubdirectories = true;
            }
            if (_ConfigReader == null)
            {
                lock (_lock)
                {
                    _ConfigReader = new ConfigReader();
                }
            }

            return(_ConfigReader);
        }