Share via

save All files when using fillesystemwacther

MiPakTeh 1,476 Reputation points
2021-03-14T01:33:34.04+00:00

Hi All, I use a filesystemwacther to listening what files is coming in my computer.How to write a code to save all that files in the new folder? or I need to move to new folder. bellow some code I try follow.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Learning_12
{
    public partial class Form1 : Form
    {

        List<string> filesAdded = new List<string>();
        FileSystemWatcher Guarding = new FileSystemWatcher();

        public Form1()
        {
            InitializeComponent();

        }

        void OnChanged(object source, FileSystemEventArgs e)
        {
            filesAdded.Add(e.FullPath);
            listView1.VirtualListSize = filesAdded.Count();

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
            listView1.RetrieveVirtualItem += new RetrieveVirtualItemEventHandler(listView1_RetrieveVirtualItem);
            listView1.VirtualMode = true;
            listView1.View = View.Details;
            listView1.GridLines = true;
            listView1.Columns.Add("Filename", 600);      // Creates column headings
            string sOri = @"C:\";
            Guarding.Path = sOri;
            Guarding.IncludeSubdirectories = true;
            Guarding.Created += new FileSystemEventHandler(OnChanged);
            Guarding.EnableRaisingEvents = true;
        }

        void listView1_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
        {
            var item = new ListViewItem();
            if (filesAdded.Count > 0)
            {
                item.Text = filesAdded[e.ItemIndex];
            }
            e.Item = item;

            System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\Users\\suhai\\Documents\\AS.txt");
            file.WriteLine(item);

            file.Close();



        }

        private void button1_Click(object sender, EventArgs e)
        {

        }


    }
}
Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

0 comments No comments

Answer accepted by question author

Karen Payne MVP 35,606 Reputation points Volunteer Moderator
2021-03-14T19:35:39.277+00:00

Hello,

The following should be considered a basic code sample which you can modify to meet your exact needs. This code when pressing the start button begins monitoring a folder for .txt files, change to another extension, . etc. and if the project targets .NET Core there is a Filters property.

Make sure to read the comments.

Class

This class implements FileSystemWatcher

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; }  
          
        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)  
            {  
                Debug.WriteLine($"Message: {ex.Message}");  
                Debug.WriteLine("Stacktrace:");  
                Debug.WriteLine(ex.StackTrace);  
                Debug.WriteLine("");  
                  
                DisplayException(ex.InnerException);  
            }  
        }  
    }  
}  

Form code

Two buttons

using System;  
using System.ComponentModel;  
using System.Windows.Forms;  
  
namespace WindowsFormsApp1  
{  
    public partial class Form1 : Form  
    {  
        private readonly FileOperations _fileOperations =   
            new FileOperations("Watch path","Move to path", "*.txt");  
          
        public Form1()  
        {  
            InitializeComponent();  
            Closing += OnClosing;  
        }  
  
        private void OnClosing(object sender, CancelEventArgs e)  
        {  
            _fileOperations.Stop();  
        }  
  
        private void StartButton_Click(object sender, EventArgs e)  
        {  
            _fileOperations.Start();  
        }  
  
        private void StopButton_Click(object sender, EventArgs e)  
        {  
            _fileOperations.Stop();  
        }  
    }  
}  
  

Was this answer helpful?


0 additional answers

Sort by: Most helpful

Your answer

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