private static void AssertTimedOut(WaitForChangedResult result)
 {
     Assert.Equal(0, (int)result.ChangeType);
     Assert.Null(result.Name);
     Assert.Null(result.OldName);
     Assert.True(result.TimedOut);
 }
        public static void WaitForChangedResult_OldName_Roundtrip(string name)
        {
            var result = new WaitForChangedResult();

            result.OldName = name;
            Assert.Equal(name, result.OldName);
        }
        public static void WaitForChangedResult_ChangeType_Roundtrip(WatcherChangeTypes changeType)
        {
            var result = new WaitForChangedResult();

            result.ChangeType = changeType;
            Assert.Equal(changeType, result.ChangeType);
        }
Example #4
0
        WaitForChangedResult waitForChangedHandler(string directoryPath, string filter,
                                                   WatcherChangeTypes watcherChangeTypes, int timeOut)
        {
            if (watcherChangeTypes != WatcherChangeTypes.Created)
            {
                throw new NotImplementedException(watcherChangeTypes.ToString());
            }
            var filesList = new ArrayList(Directory.GetFiles(directoryPath, filter));

            var waitForChangedResult = new WaitForChangedResult();

            while (true)
            {
                var newFilesList = new ArrayList(Directory.GetFiles(directoryPath, filter));
                foreach (string file in newFilesList)
                {
                    if (!filesList.Contains(file))
                    {
                        waitForChangedResult.ChangeType = WatcherChangeTypes.Created;
                        waitForChangedResult.Name       = file;
                        return(waitForChangedResult);
                    }
                }
            }
        }
Example #5
0
        //Monitorar
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                loadXml();
            }
            catch (Exception)
            {
                MessageBox.Show("Arquivo de ConfiguraĆ§Ć£o nao encontrado \r\n Ou contate o fornecedor: \r\n Bruno Vieira Roberti: 970146532");
            }

            try
            {
                fileSystemWatcher1.Path = textBox1.Text;

                fileSystemWatcher1.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.CreationTime;

                fileSystemWatcher1.EnableRaisingEvents = true;

                fileSystemWatcher1.IncludeSubdirectories = true;

                CheckForIllegalCrossThreadCalls = false;

                WaitForChangedResult wcr = fileSystemWatcher1.WaitForChanged(WatcherChangeTypes.All, 10000);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Verifique a pasta monitorada / " + ex.Message + "Ou contate o fornecedor: \r\n Bruno Vieira Roberti: 970146532");
            }
        }
Example #6
0
        public static string Waitforfilechange(string path, string filter, int timeout)
        {
            FileSystemWatcher    watcher = new FileSystemWatcher(path, filter);
            WaitForChangedResult result  = watcher.WaitForChanged(WatcherChangeTypes.All, timeout);

            return(result.Name);
        }
 private static void CreateSolutionDirectory()
 {
     if (Directory.Exists(SolutionFolderPath))
     {
         var watcher = new FileSystemWatcher(SolutionFolderPath);
         try
         {
             Directory.Delete(SolutionFolderPath, true);
         }
         catch (UnauthorizedAccessException)
         {
             // MSBuild sometimes persists and holds a handle on a file in the solution package directory.
             KillMsBuild();
             Directory.Delete(SolutionFolderPath, true);
         }
         if (Directory.Exists(SolutionFolderPath))
         {
             // Allow Directory.Delete to finish before creating.
             try
             {
                 WaitForChangedResult result = watcher.WaitForChanged(WatcherChangeTypes.Deleted, 1000);
                 if (result.TimedOut && Directory.Exists(SolutionFolderPath))
                 {
                     throw new TimeoutException($"Time out waiting for deletion of {SolutionFolderPath}");
                 }
             }
             catch (FileNotFoundException)
             {
                 // Directory was deleted between the "if(exists)" and the "watcher.WaitForChanged".
             }
         }
     }
     Directory.CreateDirectory(SolutionFolderPath);
 }
Example #8
0
        public static void WaitForZipCreation(string path, string fileName)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentNullException(nameof(path));
            }
            if (string.IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentNullException(nameof(fileName));
            }

            FileSystemWatcher fsw = null;

            try
            {
                fsw = new FileSystemWatcher();
                string[] data = new string[] { path, fileName };

                fsw.Path   = path;
                fsw.Filter = fileName;

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

                Task work = Task.Run(() =>
                {
                    try
                    {
                        Thread.Sleep(1000);

                        if (data.Length == 2)
                        {
                            string dataPath = data[0];
                            string dataFile = path + data[1];
                            Console.WriteLine($"Creating {dataFile} in task...");

                            FileStream fileStream = File.Create(dataFile);
                            fileStream.Close();
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                });

                WaitForChangedResult result =
                    fsw.WaitForChanged(WatcherChangeTypes.Created, 3000);
                Console.WriteLine($"{result.Name} created at {path}.");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                File.Delete(fileName);
                fsw?.Dispose();
            }
        }
        private void WaitForUnlock()
        {
            using (FileSystemWatcher watcher = new FileSystemWatcher(GetLockFileDirectory(), GetLockFilename()))
            {
                while (true)
                {
                    if (IsLocked() != true)
                    {
                        return;
                    }

                    /*
                     * Wait for the lock file to be deleted. If the lock file has
                     * already been deleted then this call will wait indefinitely,
                     * which is a bit odd. You would think that it would just drop
                     * through.
                     */
                    WaitForChangedResult result = watcher.WaitForChanged(WatcherChangeTypes.Deleted, 10);
                    if (result.TimedOut != true)
                    {
                        // The lock file has been deleted, so the database is now unlocked
                        return;
                    }
                }
            }
        }
Example #10
0
        private static async Task Test1()
        {
            var tcs = new TaskCompletionSource <object>();

            string path = Directory.GetCurrentDirectory() + "\\data";

            using (var fileSystemWatcher = new FileSystemWatcher())
            {
                using (var physicalFilesWatcher = new PhysicalFilesWatcher(path + Path.DirectorySeparatorChar, fileSystemWatcher, pollForChanges: false))
                {
                    using (var provider = new PhysicalFileProvider(path))
                    {
                        var token = provider.Watch("*.txt");
                        //Assert.NotNull(token);
                        //Assert.False(token.HasChanged);
                        //Assert.True(token.ActiveChangeCallbacks);

                        WaitForChangedResult result = fileSystemWatcher.WaitForChanged(WatcherChangeTypes.All);


                        //fileSystemWatcher.Changed += new FileSystemEventArgs(WatcherChangeTypes.All, path, path));
                        //await Task.Delay(WaitTimeForTokenToFire);

                        //Assert.True(token.HasChanged);
                    }
                }
            }
            await tcs.Task.ConfigureAwait(false);
        }
        static void Main()
        {
            // Š”Š¾Š·Š“Š°Š½ŠøŠµ Š½Š°Š±Š»ŃŽŠ“Š°Ń‚ŠµŠ»Ń Šø сŠ¾ŃŃ€ŠµŠ“Š¾Ń‚Š¾Ń‡ŠµŠ½ŠøŠµ ŠµŠ³Š¾ Š²Š½ŠøŠ¼Š°Š½Šøя Š½Š° сŠøстŠµŠ¼Š½Š¾Š¼ Š“ŠøсŠŗŠµ.
            FileSystemWatcher watcher = new FileSystemWatcher {
                Path = @"D:\"
            };

            // Š—Š°Ń€ŠµŠ³ŠøстрŠøрŠ¾Š²Š°Ń‚ŃŒ Š¾Š±Ń€Š°Š±Š¾Ń‚чŠøŠŗŠø сŠ¾Š±Ń‹Ń‚ŠøŠ¹.
            watcher.Created += new FileSystemEventHandler(WatcherChanged);
            watcher.Deleted += WatcherChanged;

            // ŠŠ°Ń‡Š°Ń‚ŃŒ Š¼Š¾Š½ŠøтŠ¾Ń€ŠøŠ½Š³.
            watcher.EnableRaisingEvents = true;

            // Š”Š¾Š“ŠµŃ€Š¶Šøт сŠ²ŠµŠ“ŠµŠ½Šøя Š¾ ŠæрŠ¾ŠøŠ·Š¾ŃˆŠµŠ“шŠøх ŠøŠ·Š¼ŠµŠ½ŠµŠ½Šøях.
            // WaitForChanged - Š”ŠøŠ½Ń…Ń€Š¾Š½Š½Ń‹Š¹ Š¼ŠµŃ‚Š¾Š“, Š²Š¾Š·Š²Ń€Š°Ń‰Š°ŃŽŃ‰ŠøŠ¹ струŠŗтуру, сŠ¾Š“ŠµŃ€Š¶Š°Ń‰ŃƒŃŽ
            // сŠ²ŠµŠ“ŠµŠ½Šøя Š¾ ŠæрŠ¾ŠøŠ·Š¾ŃˆŠµŠ“шŠøх ŠøŠ·Š¼ŠµŠ½ŠµŠ½Šøях, с Š·Š°Š“Š°Š½Š½Ń‹Š¼ тŠøŠæŠ¾Š¼ ŠøŠ·Š¼ŠµŠ½ŠµŠ½ŠøŠ¹,
            // ŠŗŠ¾Ń‚Š¾Ń€Ń‹Šµ Š²Ń‹ хŠ¾Ń‚ŠøтŠµ ŠŗŠ¾Š½Ń‚Ń€Š¾Š»ŠøрŠ¾Š²Š°Ń‚ŃŒ.
            WaitForChangedResult change = watcher.WaitForChanged(WatcherChangeTypes.All);

            // Š’Š¾Š·Š²Ń€Š°Ń‰Š°ŠµŃ‚ ŠøŠ»Šø Š·Š°Š“Š°ŠµŃ‚ тŠøŠæ ŠæрŠ¾ŠøŠ·Š¾ŃˆŠµŠ“шŠµŠ³Š¾ ŠøŠ·Š¼ŠµŠ½ŠµŠ½Šøя.
            Console.WriteLine(change.ChangeType);

            // Š’Š¾Š·Š²Ń€Š°Ń‰Š°ŠµŃ‚ ŠøŠ»Šø Š·Š°Š“Š°ŠµŃ‚ ŠøŠ¼Ń фŠ°Š¹Š»Š° ŠøŠ»Šø ŠŗŠ°Ń‚Š°Š»Š¾Š³Š°, ŠŗŠ¾Ń‚Š¾Ń€Š°Ń ŠøŠ·Š¼ŠµŠ½ŠµŠ½Š°.
            Console.WriteLine(change.Name);

            // Š’Š¾Š·Š²Ń€Š°Ń‰Š°ŠµŃ‚ ŠøŠ»Šø Š·Š°Š“Š°ŠµŃ‚ ŠøŠ¼Ń ŠøсхŠ¾Š“Š½Š¾Š³Š¾ фŠ°Š¹Š»Š° ŠøŠ»Šø ŠŗŠ°Ń‚Š°Š»Š¾Š³Š°, ŠŗŠ¾Ń‚Š¾Ń€Ń‹Š¹ Š±Ń‹Š» ŠæŠµŃ€ŠµŠøŠ¼ŠµŠ½Š¾Š²Š°Š½.
            Console.WriteLine(change.OldName);

            // Š’Š¾Š·Š²Ń€Š°Ń‰Š°ŠµŃ‚ ŠøŠ»Šø Š·Š°Š“Š°ŠµŃ‚ Š·Š½Š°Ń‡ŠµŠ½ŠøŠµ, ŠæŠ¾ŠŗŠ°Š·Ń‹Š²Š°ŃŽŃ‰ŠµŠµ, ŠøстŠµŠŗŠ»Š¾ Š»Šø Š²Ń€ŠµŠ¼Ń Š¾Š¶ŠøŠ“Š°Š½Šøя Š¾ŠæŠµŃ€Š°Ń†ŠøŠø.
            Console.WriteLine(change.TimedOut);

            // Š—Š°Š“ŠµŃ€Š¶ŠŗŠ°
            Console.ReadKey();
        }
Example #12
0
 public void WaitForChanged(WatcherChangeTypes changeType)
 {
     while (Program.Running)
     {
         WaitForChangedResult changeResult = _fileSystemWatcher.WaitForChanged(changeType);
         OnFileChanged(new FileSystemEventArgs(changeType, Path.GetFullPath(changeResult.Name), changeResult.Name));
     }
 }
 public static void WaitForChangedResult_DefaultValues()
 {
     var result = new WaitForChangedResult();
     Assert.Equal((WatcherChangeTypes)0, result.ChangeType);
     Assert.Null(result.Name);
     Assert.Null(result.OldName);
     Assert.False(result.TimedOut);
 }
Example #14
0
        static void Main(string[] args)
        {
            Process process = new Process();

            process.StartInfo.FileName               = "cmd.exe";
            process.StartInfo.WorkingDirectory       = "f5";
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            //process.StartInfo.RedirectStandardError = true;

            Regex regexEmbedded   = new Regex(@"([0-9]+) bits \([0-9]+ bytes\) embedded", RegexOptions.RightToLeft | RegexOptions.Compiled);
            Regex regexResolution = new Regex("[0-9]+ x [0-9]+", RegexOptions.Compiled);

            DirectoryInfo directoryInfo = new DirectoryInfo(PathToImages);

            FileInfo[] images = directoryInfo.GetFiles("*", SearchOption.TopDirectoryOnly);

            Console.Write("Specify delimiter in csv file: ");
            string delimiter = Char.ConvertFromUtf32(Console.Read());
            string header    = string.Join(delimiter, "File name", "Resolution", "Size of embedded information(bits)",
                                           "Size of base image(bits)", "% of embedded information");

            using (FileSystemWatcher watcher = new FileSystemWatcher(PathToImages, "*.jpg"))
                using (StreamWriter sw = new StreamWriter("result.csv", false, Encoding.UTF8))
                {
                    sw.WriteLineAsync(header);
                    //watcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite;

                    foreach (FileInfo image in images)
                    {
                        process.StartInfo.Arguments = Arguments + image.Name;
                        process.Start();

                        Task <string> readOutput = process.StandardOutput.ReadToEndAsync();

                        WaitForChangedResult result = watcher.WaitForChanged(WatcherChangeTypes.Created);
                        string pathToImage          = PathToImages + result.Name;

                        readOutput.Wait();
                        string output = readOutput.Result;

                        string resolution   = regexResolution.Match(output).Value;
                        ulong  embeddedBits = ulong.Parse(regexEmbedded.Match(output).Groups[1].Value);

                        process.WaitForExit();

                        long length = new FileInfo(pathToImage).Length;

                        string line = string.Join(delimiter, image.Name, resolution, embeddedBits, length * 8,
                                                  string.Format("{0:0.00}", (embeddedBits * 100) / (double)(length * 8)));
                        sw.WriteLineAsync(line);

                        Console.WriteLine(result.Name);

                        File.Delete(pathToImage);
                    }
                }
        }
        public static void WaitForChangedResult_DefaultValues()
        {
            var result = new WaitForChangedResult();

            Assert.Equal((WatcherChangeTypes)0, result.ChangeType);
            Assert.Null(result.Name);
            Assert.Null(result.OldName);
            Assert.False(result.TimedOut);
        }
Example #16
0
        /// <summary>
        /// _
        /// </summary>
        /// <param name="directoryPath"></param>
        /// <returns>true if the file exists at the given time</returns>
        public static bool WaitForFileToBeCreated(string directoryPath, int milliSec, string filter)
        {
            var fileAutomation = new FileAutomation();
            WaitForChangedResult waitForChanged = fileAutomation.WaitForChanged(directoryPath, filter,
                                                                                WatcherChangeTypes.Created, milliSec);
            bool b = waitForChanged.Name + "" != "";

            return(b);
        }
 public static void WaitForChangedResult_TimedOut_Roundtrip()
 {
     var result = new WaitForChangedResult();
     result.TimedOut = true;
     Assert.True(result.TimedOut);
     result.TimedOut = false;
     Assert.False(result.TimedOut);
     result.TimedOut = true;
     Assert.True(result.TimedOut);
 }
Example #18
0
        // Run the command after change
        void RunCommand(object sender, WaitForChangedResult e) {
            var workDir = _config.WorkingDirectory;
            if (String.IsNullOrEmpty(workDir)) {
                var dir = _config.Directory;
                if (String.IsNullOrEmpty(dir))
                    dir = Directory.GetCurrentDirectory();
                workDir = Path.GetDirectoryName(Path.Combine(dir, e.Name));
            }

            var tokens = _config.Command
                .Split(new[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries);

            string @event = null;

            switch (e.ChangeType) {
                case WatcherChangeTypes.Created:
                    @event = "created";
                    break;
                case WatcherChangeTypes.Changed:
                    @event = "modified";
                    break;
                case WatcherChangeTypes.Deleted:
                    @event = "deleted";
                    break;
                case WatcherChangeTypes.Renamed:
                    @event = "renamed";
                    break;
            }

            var cmd = tokens[0];
            var args = tokens.Skip(1)
                .FirstOrDefault()
                ?.Replace("%event", @event)
                .Replace("%pathBefore", e.OldName)
                .Replace("%path", e.Name);

            var process = new Process() {
                StartInfo = new ProcessStartInfo {
                    FileName = cmd,
                    Arguments = args,
                    WorkingDirectory = workDir,
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true
                }
            };

            process.OutputDataReceived += OutputReceived;
            process.ErrorDataReceived += ErrorReceived;

            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();
            process.WaitForExit();
        }
        public static void WaitForChangedResult_TimedOut_Roundtrip()
        {
            var result = new WaitForChangedResult();

            result.TimedOut = true;
            Assert.True(result.TimedOut);
            result.TimedOut = false;
            Assert.False(result.TimedOut);
            result.TimedOut = true;
            Assert.True(result.TimedOut);
        }
Example #20
0
        public C1WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType)
        {
            WaitForChangedResult result = _fileSystemWatcher.WaitForChanged(changeType);

            return(new C1WaitForChangedResult
            {
                Name = result.Name,
                OldName = result.OldName,
                ChangeType = result.ChangeType,
                TimedOut = result.TimedOut
            });
        }
Example #21
0
        void program()
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            fileSystemWatcher1.Path = folderBrowserDialog1.SelectedPath;
            fileSystemWatcher1.IncludeSubdirectories = true;
            fileSystemWatcher1.NotifyFilter         |= NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.LastAccess | NotifyFilters.Size;

            while (true)
            {
                WaitForChangedResult w = fileSystemWatcher1.WaitForChanged(WatcherChangeTypes.All);
                label1.Text = w.Name + " " + w.ChangeType;
            }
        }
        private void When_waiting_for_file_change_while_watcher_was_not_running_it_must_be_stopped_after_wait()
        {
            // Arrange
            const string directoryToWatch = @"c:\some";
            const string fileNameToUpdate = "file.txt";

            string pathToFileToUpdate = Path.Combine(directoryToWatch, fileNameToUpdate);

            FakeFileSystem fileSystem = new FakeFileSystemBuilder()
                                        .IncludingEmptyFile(pathToFileToUpdate)
                                        .Build();

            using (FakeFileSystemWatcher watcher = fileSystem.ConstructFileSystemWatcher(directoryToWatch))
            {
                watcher.NotifyFilter = NotifyFilters.LastWrite;

                using (var listener = new FileSystemWatcherEventListener(watcher))
                {
                    watcher.EnableRaisingEvents = false;

                    fileSystem.File.SetLastWriteTimeUtc(pathToFileToUpdate, 1.January(2000));
                    Thread.Sleep(SleepTimeToEnsureOperationHasArrivedAtWatcherConsumerLoop);

                    Task.Run(() =>
                    {
                        Thread.Sleep(SleepTimeToEnsureWaiterInitializationHasCompleted);
                        fileSystem.File.SetLastWriteTimeUtc(pathToFileToUpdate, 2.January(2000));
                    });

                    // Act
                    WaitForChangedResult result =
                        watcher.WaitForChanged(WatcherChangeTypes.Changed, MaxTestDurationInMilliseconds);

                    fileSystem.File.SetLastWriteTimeUtc(pathToFileToUpdate, 3.January(2000));

                    watcher.FinishAndWaitForFlushed(MaxTestDurationInMilliseconds);

                    // Assert
                    result.TimedOut.Should().BeFalse();
                    result.ChangeType.Should().Be(WatcherChangeTypes.Changed);
                    result.Name.Should().Be(fileNameToUpdate);
                    result.OldName.Should().BeNull();

                    string text = string.Join(Environment.NewLine, listener.GetEventsCollectedAsText());
                    text.Should().Be(@"
                        * file.txt
                        ".TrimLines());
                }
            }
        }
Example #23
0
        public bool WaitForChange(out WaitForChangedResult result, WatcherChangeTypes types, int timeout)
        {
            foreach (var fileWatcher in fileWatchers)
            {
                var newResult = fileWatcher.WaitForChanged(types, timeout);
                if (newResult.ChangeType != 0 || newResult.TimedOut)
                {
                    result = newResult;
                    return(false);
                }
            }

            result = new WaitForChangedResult();
            return(true);
        }
Example #24
0
    public static void Main()
    {
        FileSystemWatcher watcher = new FileSystemWatcher(@"c:\", "*.*");
        // only rename event
        WaitForChangedResult result = watcher.WaitForChanged(WatcherChangeTypes.Changed | WatcherChangeTypes.Renamed);

        switch (result.ChangeType)
        {
        case WatcherChangeTypes.Changed:
            Console.WriteLine("{0}: File '{1}' was changed", DateTime.Now, result.Name);
            break;

        case WatcherChangeTypes.Renamed:
            Console.WriteLine("{0}: File '{1}' was renamed to '{2}'", DateTime.Now, result.OldName, result.Name);
            break;
        }
    }
        private void When_waiting_for_file_change_multiple_times_it_must_succeed()
        {
            // Arrange
            const string directoryToWatch = @"c:\some";
            const string fileNameToUpdate = "file.txt";

            string pathToFileToUpdate = Path.Combine(directoryToWatch, fileNameToUpdate);

            FakeFileSystem fileSystem = new FakeFileSystemBuilder()
                                        .IncludingEmptyFile(pathToFileToUpdate)
                                        .Build();

            // ReSharper disable once ConvertToLocalFunction
            Action <DateTime> updateCreationTimeAction = creationTimeUtc =>
            {
                Thread.Sleep(SleepTimeToEnsureWaiterInitializationHasCompleted);
                fileSystem.File.SetCreationTimeUtc(pathToFileToUpdate, creationTimeUtc);
            };

            using (FakeFileSystemWatcher watcher = fileSystem.ConstructFileSystemWatcher(directoryToWatch))
            {
                watcher.NotifyFilter = NotifyFilters.CreationTime;

                Task.Run(() => updateCreationTimeAction(1.January(2000)));

                // Act
                WaitForChangedResult result1 = watcher.WaitForChanged(WatcherChangeTypes.Changed, MaxTestDurationInMilliseconds);

                Task.Run(() => updateCreationTimeAction(2.January(2000)));

                WaitForChangedResult result2 = watcher.WaitForChanged(WatcherChangeTypes.Changed, MaxTestDurationInMilliseconds);

                // Assert
                result1.TimedOut.Should().BeFalse();
                result1.ChangeType.Should().Be(WatcherChangeTypes.Changed);
                result1.Name.Should().Be(fileNameToUpdate);
                result1.OldName.Should().BeNull();

                result2.TimedOut.Should().BeFalse();
                result2.ChangeType.Should().Be(WatcherChangeTypes.Changed);
                result2.Name.Should().Be(fileNameToUpdate);
                result2.OldName.Should().BeNull();
            }
        }
        private void SignalFileChangeForWaiters(WatcherChangeTypes type, string filePath)
        {
            if (_waiters == 0)
            {
                return;                // No point signaling if no one is waiting
            }
            // Getting the 'relative path' of the filePath compared to the currently monitored folder path
            string uppercaseFilePath = filePath.ToUpperInvariant();
            var    fileNameToReport  = uppercaseFilePath.Replace(_uppercasePath, string.Empty);

            lock (_latestChangeLocker)
            {
                _latestChange = new WaitForChangedResult()
                {
                    ChangeType = type, Name = fileNameToReport
                };
            }
            _changesWatchingEvent.Set();
        }
        private void When_waiting_for_file_rename_while_files_are_renamed_it_must_succeed()
        {
            // Arrange
            const string directoryToWatch = @"c:\some";
            const string sourceFileName1  = "source1.txt";
            const string targetFileName1  = "target1.txt";
            const string sourceFileName2  = "source2.txt";
            const string targetFileName2  = "target2.txt";

            string pathToSourceFile1 = Path.Combine(directoryToWatch, sourceFileName1);
            string pathToTargetFile1 = Path.Combine(directoryToWatch, targetFileName1);
            string pathToSourceFile2 = Path.Combine(directoryToWatch, sourceFileName2);
            string pathToTargetFile2 = Path.Combine(directoryToWatch, targetFileName2);

            FakeFileSystem fileSystem = new FakeFileSystemBuilder()
                                        .IncludingEmptyFile(pathToSourceFile1)
                                        .IncludingEmptyFile(pathToSourceFile2)
                                        .Build();

            using (FakeFileSystemWatcher watcher = fileSystem.ConstructFileSystemWatcher(directoryToWatch))
            {
                watcher.NotifyFilter = NotifyFilters.FileName;

                Task.Run(() =>
                {
                    // ReSharper disable once AccessToDisposedClosure
                    BlockUntilStarted(watcher);

                    fileSystem.File.Move(pathToSourceFile1, pathToTargetFile1);
                    fileSystem.File.Move(pathToSourceFile2, pathToTargetFile2);
                });

                // Act
                WaitForChangedResult result = watcher.WaitForChanged(WatcherChangeTypes.Renamed, MaxTestDurationInMilliseconds);

                // Assert
                result.TimedOut.Should().BeFalse();
                result.ChangeType.Should().Be(WatcherChangeTypes.Renamed);
                result.Name.Should().Be(targetFileName1);
                result.OldName.Should().Be(sourceFileName1);
            }
        }
Example #28
0
        /// <summary>
        /// This method is to be used for win98,winME
        /// </summary>
        /// <param name="directoryPath"></param>
        /// <param name="filter"></param>
        /// <param name="watcherChangeTypes"></param>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public WaitForChangedResult WaitForChanged(string directoryPath, string filter,
                                                   WatcherChangeTypes watcherChangeTypes,
                                                   int timeOut)
        {
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                var watcher = new FileSystemWatcher(directoryPath, filter);
                WaitForChangedResult waitForChanged = watcher.WaitForChanged(watcherChangeTypes, timeOut);
                return(waitForChanged);
            }

            waitForChangedDelegate d   = waitForChangedHandler;
            IAsyncResult           res = d.BeginInvoke(directoryPath, filter, watcherChangeTypes, timeOut, null, null);

            if (res.IsCompleted == false)
            {
                res.AsyncWaitHandle.WaitOne(timeOut, false);
            }
            return(res.IsCompleted ? d.EndInvoke(res) : new WaitForChangedResult());
        }
        private void When_waiting_for_change_it_must_apply_filters()
        {
            // Arrange
            const string directoryToWatch = @"c:\some";

            string pathToMismatchingFile      = Path.Combine(directoryToWatch, "OtherName.txt");
            string pathToMismatchingDirectory = Path.Combine(directoryToWatch, "SomeFolderIgnored");
            string pathToMatchingFile         = Path.Combine(directoryToWatch, "Subfolder", "SomeFile.txt");

            FakeFileSystem fileSystem = new FakeFileSystemBuilder()
                                        .IncludingEmptyFile(pathToMismatchingFile)
                                        .IncludingDirectory(Path.Combine(directoryToWatch, "Subfolder"))
                                        .IncludingEmptyFile(pathToMatchingFile)
                                        .Build();

            using (FakeFileSystemWatcher watcher = fileSystem.ConstructFileSystemWatcher(directoryToWatch))
            {
                watcher.NotifyFilter          = NotifyFilters.FileName | NotifyFilters.Size;
                watcher.IncludeSubdirectories = true;
                watcher.Filter = "Some*";

                Task.Run(() =>
                {
                    // ReSharper disable once AccessToDisposedClosure
                    BlockUntilStarted(watcher);

                    fileSystem.Directory.CreateDirectory(pathToMismatchingDirectory);
                    fileSystem.File.AppendAllText(pathToMismatchingFile, "IgnoreMe");
                    fileSystem.File.AppendAllText(pathToMatchingFile, "NotifyForMe");
                });

                // Act
                WaitForChangedResult result = watcher.WaitForChanged(WatcherChangeTypes.All, MaxTestDurationInMilliseconds);

                // Assert
                result.TimedOut.Should().BeFalse();
                result.ChangeType.Should().Be(WatcherChangeTypes.Changed);
                result.Name.Should().Be(@"Subfolder\SomeFile.txt");
                result.OldName.Should().BeNull();
            }
        }
        private void When_waiting_for_changes_while_timeout_expires_it_must_succeed()
        {
            // Arrange
            const string directoryToWatch = @"c:\some";

            FakeFileSystem fileSystem = new FakeFileSystemBuilder()
                                        .IncludingDirectory(directoryToWatch)
                                        .Build();

            using (FakeFileSystemWatcher watcher = fileSystem.ConstructFileSystemWatcher(directoryToWatch))
            {
                // Act
                WaitForChangedResult result = watcher.WaitForChanged(WatcherChangeTypes.All, 1000);

                // Assert
                result.TimedOut.Should().BeTrue();
                result.ChangeType.Should().Be(0);
                result.Name.Should().BeNull();
                result.OldName.Should().BeNull();
            }
        }
        private void When_waiting_for_file_change_while_file_attributes_are_changed_it_must_succeed()
        {
            // Arrange
            const string directoryToWatch  = @"c:\some";
            const string fileNameToUpdate1 = "file1.txt";
            const string fileNameToUpdate2 = "file2.txt";

            string pathToFileToUpdate1 = Path.Combine(directoryToWatch, fileNameToUpdate1);
            string pathToFileToUpdate2 = Path.Combine(directoryToWatch, fileNameToUpdate2);

            FakeFileSystem fileSystem = new FakeFileSystemBuilder()
                                        .IncludingEmptyFile(pathToFileToUpdate1)
                                        .IncludingEmptyFile(pathToFileToUpdate2)
                                        .Build();

            using (FakeFileSystemWatcher watcher = fileSystem.ConstructFileSystemWatcher(directoryToWatch))
            {
                watcher.NotifyFilter = NotifyFilters.Attributes;

                Task.Run(() =>
                {
                    // ReSharper disable once AccessToDisposedClosure
                    BlockUntilStarted(watcher);

                    fileSystem.File.SetAttributes(pathToFileToUpdate1, FileAttributes.System);
                    fileSystem.File.SetAttributes(pathToFileToUpdate2, FileAttributes.System);
                });

                // Act
                WaitForChangedResult result = watcher.WaitForChanged(WatcherChangeTypes.Changed, MaxTestDurationInMilliseconds);

                // Assert
                result.TimedOut.Should().BeFalse();
                result.ChangeType.Should().Be(WatcherChangeTypes.Changed);
                result.Name.Should().Be(fileNameToUpdate1);
                result.OldName.Should().BeNull();
            }
        }
        private void When_waiting_for_directory_deletion_while_directories_are_deleted_it_must_succeed()
        {
            // Arrange
            const string directoryToWatch       = @"c:\some";
            const string directoryNameToDelete1 = "subfolder1";
            const string directoryNameToDelete2 = "subfolder2";

            string pathToDirectoryToDelete1 = Path.Combine(directoryToWatch, directoryNameToDelete1);
            string pathToDirectoryToDelete2 = Path.Combine(directoryToWatch, directoryNameToDelete2);

            FakeFileSystem fileSystem = new FakeFileSystemBuilder()
                                        .IncludingDirectory(pathToDirectoryToDelete1)
                                        .IncludingDirectory(pathToDirectoryToDelete2)
                                        .Build();

            using (FakeFileSystemWatcher watcher = fileSystem.ConstructFileSystemWatcher(directoryToWatch))
            {
                watcher.NotifyFilter = NotifyFilters.DirectoryName;

                Task.Run(() =>
                {
                    // ReSharper disable once AccessToDisposedClosure
                    BlockUntilStarted(watcher);

                    fileSystem.Directory.Delete(pathToDirectoryToDelete1);
                    fileSystem.Directory.Delete(pathToDirectoryToDelete2);
                });

                // Act
                WaitForChangedResult result = watcher.WaitForChanged(WatcherChangeTypes.Deleted, MaxTestDurationInMilliseconds);

                // Assert
                result.TimedOut.Should().BeFalse();
                result.ChangeType.Should().Be(WatcherChangeTypes.Deleted);
                result.Name.Should().Be(directoryNameToDelete1);
                result.OldName.Should().BeNull();
            }
        }
 public static void WaitForChangedResult_OldName_Roundtrip(string name)
 {
     var result = new WaitForChangedResult();
     result.OldName = name;
     Assert.Equal(name, result.OldName);
 }
 public static void WaitForChangedResult_ChangeType_Roundtrip(WatcherChangeTypes changeType)
 {
     var result = new WaitForChangedResult();
     result.ChangeType = changeType;
     Assert.Equal(changeType, result.ChangeType);
 }
 private static void AssertTimedOut(WaitForChangedResult result)
 {
     Assert.Equal(0, (int)result.ChangeType);
     Assert.Null(result.Name);
     Assert.Null(result.OldName);
     Assert.True(result.TimedOut);
 }