question

MiPakTeh-6272 avatar image
0 Votes"
MiPakTeh-6272 asked karenpayneoregon commented

save All files when using fillesystemwacther

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)
         {
    
         }
    
    
     }
 }
dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

karenpayneoregon avatar image
0 Votes"
karenpayneoregon answered karenpayneoregon commented

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();
         }
     }
 }







· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

How use virtual mode Listview.

0 Votes 0 ·

If my code solved your initial question then you need to ask about virtual mode of a ListView in a new post. Otherwise indicate how the code does not answer your question.

0 Votes 0 ·