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