FileSystemWacther and file to copy or move another Directory

MiPakTeh 1,476 Reputation points
2022-01-01T07:23:30.453+00:00

Hi All,

What try to do;

Monitoring all file coming in my computer using filesystemwacther.Put all in Listbox1.
From ListBox1 move to some Directory or may be can do direct from filesystemwacther to difference Directory.
Bellow method, I try to test.

Thank.

using System;  
using System.Collections.Generic;  
using System.ComponentModel;  
using System.Data;  
using System.Drawing;  
using System.IO;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  
using System.Windows.Forms;  
  
namespace TestFor  
{  
    public partial class Form1 : Form  
    {  
  
        public Form1()  
        {  
            InitializeComponent();  
        }  
  
        private void button1_Click(object sender, EventArgs e)  
        {  
            var watcher = new FileSystemWatcher(@"C:\");  
            watcher.NotifyFilter = NotifyFilters.Attributes  
                                 | NotifyFilters.CreationTime  
                                 | NotifyFilters.DirectoryName  
                                 | NotifyFilters.FileName  
                                 | NotifyFilters.LastAccess  
                                 | NotifyFilters.LastWrite  
                                 | NotifyFilters.Security  
                                 | NotifyFilters.Size;  
  
            watcher.Created += OnCreated;  
            watcher.IncludeSubdirectories = true;  
            watcher.EnableRaisingEvents = true;  
  
            Console.WriteLine("Press enter to exit.");  
            Console.ReadLine();  
        }  
  
        private void OnCreated(object sender, FileSystemEventArgs e)  
        {  
            string value = $"Created: {e.FullPath}";  
            listBox1.Invoke(new Action(() => listBox1.Items.Add(value)));  
  
            DirectoryInfo di = new DirectoryInfo(@"C:\\Users\\family\\Documents\\Monitor");  
            try  
            {  
                if (di.Exists)  
                {  
                    Console.WriteLine("That path exists already.");  
                    return;  
                }  
                di.Create();  
                Console.WriteLine("The directory was created successfully.");  
                di.Delete();  
                Console.WriteLine("The directory was deleted successfully.");  
            }  
            catch (Exception)  
            {  
                Console.WriteLine("The process failed: {0}", e.ToString());  
            }  
            finally { }  
  
            var itemsToMove = listBox1.Items.Cast<DirectoryInfo>();  
            var directoriesTheyAreIn = itemsToMove.Select(x => x.GetDirectories());  
  
            var cleanDirectoriesList = directoriesTheyAreIn.Distinct();  
            //As many file can be in the same Dir we only need to move the dire once to move those file.  
  
            foreach (var path in cleanDirectoriesList)  
            {  
                // here you have to craft your destination directory  
                string destinationDirectory = @"C:\\Users\\family\\Documents\\Monitor";  
                Directory.Move(path.ToString(), destinationDirectory);  
            }  
  
        }  
    }  
}  

 

  
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2022-01-02T12:19:44.767+00:00

    I don't see any reason for this to not work other than invoking Start method e.g.

    Create instance

    private readonly FileOperations _fileOperations = 
        new FileOperations("C:\\OED", "C:\\uisides", "*.txt");
    

    Fire it up

    private void StartButton_Click(object sender, EventArgs e)
    {
     _fileOperations.Start();
    }
    

    Source

    using System;
    using System.Diagnostics;
    using System.IO;
    using static System.IO.Path;
    
    namespace WindowsFormsApp1
    {
        public class FileOperations : FileSystemWatcher
        {
            /// <summary>
            /// Path to check for new files
            /// </summary>
            public string MonitorPath { get; set; }
            /// <summary>
            /// Path to move file(s) too
            /// </summary>
            public string TargetPath { get; set; }
    
            /// <summary>
            /// Responsible for watching a folder, move new files to a
            /// designated folder.
            /// </summary>
            /// <param name="monitorPath">Folder to monitor</param>
            /// <param name="targetPath">Folder to move files to</param>
            /// <param name="extension">Extension to watch for</param>
            /// <remarks>
            /// Might want to determine if the monitorPath and targetPath exits in
            /// the constructor or prior to using this code.
            /// </remarks>
            public FileOperations(string monitorPath, string targetPath, string extension)
            {
                MonitorPath = monitorPath;
                TargetPath = targetPath;
    
                Created += OnCreated;
                Error += OnError;
    
                Path = MonitorPath;
                Filter = extension;
    
                EnableRaisingEvents = true;
    
                NotifyFilter = NotifyFilters.Attributes
                               | NotifyFilters.CreationTime
                               | NotifyFilters.DirectoryName
                               | NotifyFilters.FileName
                               | NotifyFilters.LastAccess
                               | NotifyFilters.LastWrite
                               | NotifyFilters.Security
                               | NotifyFilters.Size;
            }
    
    
            private void OnCreated(object sender, FileSystemEventArgs e)
            {
    
                try
                {
    
                    var targetFile = Combine(TargetPath, GetFileName(e.FullPath));
                    if (File.Exists(targetFile))
                    {
                        File.Delete(targetFile);
                    }
    
                    File.Move(e.FullPath,targetFile);
                }
                catch (Exception exception)
                {
                    Debug.WriteLine(exception.Message);
                }
            }
    
            public void Start()
            {
                EnableRaisingEvents = true;
            }
    
            public void Stop()
            {
                EnableRaisingEvents = false;
            }
    
            private static void OnError(object sender, ErrorEventArgs e) => DisplayException(e.GetException());
            /// <summary>
            /// For debug purposes
            /// For a production environment write to a log file
            /// </summary>
            /// <param name="ex"></param>
            private static void DisplayException(Exception ex)
            {
                if (ex == null) return;
                Debug.WriteLine($"Message: {ex.Message}");
                Debug.WriteLine("Stacktrace:");
                Debug.WriteLine(ex.StackTrace);
                Debug.WriteLine("");
    
                DisplayException(ex.InnerException);
            }
        }
    }
    

2 additional answers

Sort by: Most helpful
  1. M0ment 41 Reputation points
    2022-01-01T19:11:01.823+00:00

    Hello there.
    First of all, "C:\\Users\\family\\Documents\\Monitor" will register as "C:\Users\family\Documents\Monitor", but @"C:\\Users\\family\\Documents\\Monitor" will register as "C:\\Users\\family\\Documents\\Monitor".
    With that out of the way, I still do not know what you are asking. Are you getting any errors? Does something not work? You can use the Directory class to do everything you want.

    With regards,
    Alvin.


  2. MiPakTeh 1,476 Reputation points
    2022-01-08T03:11:51.093+00:00

    Karen, still not working.Here is Output message.

    'WindowsFormsApp1.exe' (CLR v4.0.30319: DefaultDomain): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll'.
    'WindowsFormsApp1.exe' (CLR v4.0.30319: DefaultDomain): Loaded 'C:\Users\family\source\repos\WindowsFormsApp1\WindowsFormsApp1\bin\Debug\WindowsFormsApp1.exe'. Symbols loaded.
    'WindowsFormsApp1.exe' (CLR v4.0.30319: WindowsFormsApp1.exe): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Windows.Forms\v4.0_4.0.0.0__b77a5c561934e089\System.Windows.Forms.dll'.
    'WindowsFormsApp1.exe' (CLR v4.0.30319: WindowsFormsApp1.exe): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c561934e089\System.dll'.
    'WindowsFormsApp1.exe' (CLR v4.0.30319: WindowsFormsApp1.exe): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Drawing\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Drawing.dll'.
    'WindowsFormsApp1.exe' (CLR v4.0.30319: WindowsFormsApp1.exe): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll'.
    'WindowsFormsApp1.exe' (CLR v4.0.30319: WindowsFormsApp1.exe): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Core\v4.0_4.0.0.0__b77a5c561934e089\System.Core.dll'.
    'WindowsFormsApp1.exe' (CLR v4.0.30319: WindowsFormsApp1.exe): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Xml\v4.0_4.0.0.0__b77a5c561934e089\System.Xml.dll'.
    Exception thrown: 'System.IO.FileNotFoundException' in mscorlib.dll
    Could not find file 'C:\Users\family\AppData\Local\Temp\d15d56a2-aae3-4c2e-a0a5-4f4737fb0044.PackageExtraction'.
    Exception thrown: 'System.UnauthorizedAccessException' in mscorlib.dll
    Access to the path 'C:\Users\family\Documents\Monitor\~DF7747CCCA41D92049.TMP' is denied.
    The thread 0xdb0 has exited with code 0 (0x0).
    The thread 0x39c8 has exited with code 0 (0x0).
    Exception thrown: 'System.IO.IOException' in mscorlib.dll
    The process cannot access the file because it is being used by another process.
    Exception thrown: 'System.IO.IOException' in mscorlib.dll
    The process cannot access the file because it is being used by another process.
    Exception thrown: 'System.UnauthorizedAccessException' in mscorlib.dll
    Access to the path is denied.
    The thread 0x14f8 has exited with code 0 (0x0).
    The thread 0x1cf8 has exited with code 0 (0x0).
    The thread 0x1ab0 has exited with code 0 (0x0).
    The program '[7520] WindowsFormsApp1.exe' has exited with code -1 (0xffffffff).

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.