I am fairly new to C# coding.. I am trying to setup a code that will alert me when there is an inactivity in a folder. We have a current and archive folder. Once the file is processed in the current folder it will move onto the archive folder.
I have the code to check if there are files in the current folder that's the easy part
DirectoryInfo id = new DirectoryInfo(#"C\");
FileInfo[] TXTFiles = id.GetFiles("*.txt");
if (TXTFiles.Length == 0)
{
Console.WriteLine("Files does not ");
Console.WriteLine("Checking the last processed file in the Archive directory");
Console.Read();
}
if (TXTFiles.Length != 0)
{
Console.WriteLine("Files exists ");
Console.Read();
}
So in the logic where the file does not exist I want to have an additional step to get the timestamp of the last text file that was processed. This is to check for how long there hasnt been any activity .
I am not sure how to proceed. Also instead of writing this information to a console can i send a message to a webservice
Thanks
FileSystemWatcher will be your friend :)
https://msdn.microsoft.com/fr-fr/library/system.io.filesystemwatcher(v=vs.110).aspx
using System;
using System.IO;
using System.Security.Permissions;
public class Watcher
{
public static void Main()
{
Run();
}
[PermissionSet(SecurityAction.Demand, Name="FullTrust")]
public static void Run()
{
string[] args = System.Environment.GetCommandLineArgs();
// If a directory is not specified, exit program.
if(args.Length != 2)
{
// Display the proper way to call the program.
Console.WriteLine("Usage: Watcher.exe (directory)");
return;
}
// Create a new FileSystemWatcher and set its properties.
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = args[1];
/* Watch for changes in LastAccess and LastWrite times, and
the renaming of files or directories. */
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
// Only watch text files.
watcher.Filter = "*.txt";
// Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
// Begin watching.
watcher.EnableRaisingEvents = true;
// Wait for the user to quit the program.
Console.WriteLine("Press \'q\' to quit the sample.");
while(Console.Read()!='q');
}
// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e)
{
// Specify what is done when a file is changed, created, or deleted.
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
// Specify what is done when a file is renamed.
Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
}
}
Source code from MSDN.
Related
Hello I have an error with file.Move a file to an other file with a listener to this specific folder,
I want move the file in Archive folder when a new file incomming on the folder Pending.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
namespace ListenApp
{
class Program
{
public static class Globals
{
public static string args = "//lux.pbk/Profiles/LUX/BI14H/ProfilADW7/Desktop/trade/Pending/";
public static string archivePath = "//lux.pbk/Profiles/LUX/BI14H/ProfilADW7/Desktop/trade/archive/";
}
public static void Main()
{
Run();
}
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
private static void Run()
{
/* // If a directory is not specified, exit program.
if (args.Length != 2)
{
// Display the proper way to call the program.
Console.WriteLine("Usage: Watcher.exe (directory)");
return;
}*/
// Create a new FileSystemWatcher and set its properties.
using (FileSystemWatcher watcher = new FileSystemWatcher())
{
watcher.Path = Globals.args;
// Watch for changes in LastAccess and LastWrite times, and
// the renaming of files or directories.
watcher.NotifyFilter = NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.FileName
| NotifyFilters.DirectoryName;
// Only watch text files.
watcher.Filter = "*.txt";
// Add event handlers.
watcher.Created += OnChanged;
// Begin watching.
watcher.EnableRaisingEvents = true;
// Wait for the user to quit the program.
Console.WriteLine("Press 'q' to quit the sample.");
while (Console.Read() != 'q') ;
}
}
// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e)
{
// Specify what is done when a file is changed, created, or deleted.
Console.WriteLine($"File: {e.FullPath} {e.ChangeType}");
Console.WriteLine(e.Name);
if(File.Exists(Globals.args + e.Name))
{
File.Move(Globals.args + e.Name, Globals.archivePath + e.Name); // System.IO.IOException: 'The process cannot access the file because it is being used by another process.'
}
}
}
}
On File.Move, I have a error, that said :
System.IO.IOException: 'The process cannot access the file because it
is being used by another process.'
How fix this?
the situation is this, I have a datagridview which load some data from an xml file, so, I use a function to load this information and into this function the first lines make a cleaning of the full datagridview, i'm using a FileSystemWatcher to handle events when a new file is inserted into a specific folder and refresh the table, it works fine when I only move or create one file, but when I move files to the folder, or copy & paste, the program throws an error message, I think it's because the event is firing for every copied or moved file, and it doesn't let to finish the get files method when it is cleaning again, i'm not sure if i was clear, i'm going to let you here the pieces of the code, the instance of the FileWatcher it's initialized in the constructor of the class that contains the GetFiles method
GetFiles method:
public void GetFiles()
{
ds.Clear();
this.dgArchivos.DataSource = null;
this.dgArchivos.Rows.Clear();
this.dgArchivos.Refresh();
filesPath = Clases.Utilerias.RutaArchivos;
this.lblFilePath.Text = filesPath;
DirectoryInfo di = new DirectoryInfo(filesPath);
var archivos = di.GetFiles("*.pdf");
DataRow dr;
//PASO 1 -- Cargamos el XML
string rutaConfig = string.Format(#"{0}\{1}", filesPath, "config.xml");
FileInfo fi = new FileInfo(rutaConfig);
if (fi.Exists)
{
ds.ReadXml(rutaConfig);
}
//PASO 2 -- Agregamos los archivos que no existan en el xml
foreach (var archivo in archivos)
{
if (!ExisteArchivoEnTabla(archivo.Name)) //antes de cargar los archivos a la tabla es necesario revisar si ya existe en ella
{
dr = ds.Tables[0].NewRow();
dr["FileName"] = archivo.Name;
ds.Tables[0].Rows.Add(dr);
}
}
this.dgArchivos.DataSource = ds.Tables[0];
if (dgArchivos.Rows.Count > 0)
{
int Total = (dgArchivos.Rows[0].Cells.Count - 2);
dgArchivos.Columns[Total].DefaultCellStyle.NullValue = "Preview";
}
this.getFRunning = false;
}
FileWatcherClass:
using System;
using System.IO;
using System.Security.Permissions;
using ScanScraping.App;
namespace ScanScraping.Clases
{
public class FileWatcher
{
public static frmProcessFile frm;
public FileWatcher(frmProcessFile process)
{
frm = process;
Run();
}
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public static void Run()
{
// Create a new FileSystemWatcher and set its properties.
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = Clases.Utilerias.RutaArchivos;
/* Watch for changes in LastAccess and LastWrite times, and
the renaming of files or directories. */
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
// Only watch text files.
watcher.Filter = "*.pdf";
// Add event handlers.
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnDeleted);
// Begin watching.
watcher.EnableRaisingEvents = true;
// Wait for the user to quit the program.
}
// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e)
{
// Specify what is done when a file is changed, created, or deleted.
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
frm.formPadre.xmlCreateOrUpdate();
frm.GetFiles();
}
public static void OnDeleted(object source, FileSystemEventArgs e)
{
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
string[] file = e.FullPath.Split('\\');
string fName = file[file.Length - 1];
frm.updateXML(fName);
frm.GetFiles();
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
// Specify what is done when a file is renamed.
Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
frm.formPadre.xmlCreateOrUpdate();
frm.GetFiles();
}
}
}
I was wondering if there was a way to detect if a process is deleting or encrypting a file. I am trying to make an anti-ransomware application in C# so I was wondering if anyone could help.
Any suggestions?
You want to take a look at the FileSystemWatcher class.
From the MSDN page:
using System;
using System.IO;
using System.Security.Permissions;
public class Watcher
{
public static void Main()
{
Run();
}
[PermissionSet(SecurityAction.Demand, Name="FullTrust")]
public static void Run()
{
string[] args = System.Environment.GetCommandLineArgs();
// If a directory is not specified, exit program.
if(args.Length != 2)
{
// Display the proper way to call the program.
Console.WriteLine("Usage: Watcher.exe (directory)");
return;
}
// Create a new FileSystemWatcher and set its properties.
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = args[1];
/* Watch for changes in LastAccess and LastWrite times, and
the renaming of files or directories. */
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
// Only watch text files.
watcher.Filter = "*.txt";
// Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
// Begin watching.
watcher.EnableRaisingEvents = true;
// Wait for the user to quit the program.
Console.WriteLine("Press \'q\' to quit the sample.");
while(Console.Read()!='q');
}
// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e)
{
// Specify what is done when a file is changed, created, or deleted.
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
// Specify what is done when a file is renamed.
Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
}
}
This question already has answers here:
FileSystemWatcher Changed event is raised twice
(44 answers)
Closed 7 years ago.
I am using the below code to practice FileSystemWatcher.Changed Event from here. It perfectly works fine with .txt extension, but the output is not as I expect to see when I use .pdf. It triggers one "Created" events and multiple "Changed" events.
using System;
using System.IO;
using System.Security.Permissions;
public class Watcher
{
public static void Main()
{
Run();
}
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public static void Run()
{
string[] args = System.Environment.GetCommandLineArgs();
// If a directory is not specified, exit program.
if (args.Length != 2)
{
// Display the proper way to call the program.
Console.WriteLine("Usage: Watcher.exe (directory)");
return;
}
// Create a new FileSystemWatcher and set its properties.
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = args[1];
/* Watch for changes in LastAccess and LastWrite times, and
the renaming of files or directories. */
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
// Only watch text files.
watcher.Filter = "*.pdf";
// Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
// Begin watching.
watcher.EnableRaisingEvents = true;
// Wait for the user to quit the program.
Console.WriteLine("Press \'q\' to quit the sample.");
while (Console.Read() != 'q') ;
}
// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e)
{
// Specify what is done when a file is changed, created, or deleted.
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
// Specify what is done when a file is renamed.
Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
}
}
Here is the output when I copy a PDF file to watching folder:
File: c:\test\innovation.pdf Created
File: c:\test\innovation.pdf Changed
File: c:\test\innovation.pdf Changed
File: c:\test\innovation.pdf Changed
File: c:\test\innovation.pdf Changed
Any idea why that happens?
Thanks to Ahmed Ilyas. All I needed to do was to change:
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
to
watcher.NotifyFilter = NotifyFilters.FileName;
I am using C# 3.5 on Windows 7. We have implemented a program with a FileSystemWatcher. Here, rename event is not raised. But it is working on a few systems.
What could be causing this?
There may be a timing window in your code such that not all filesystem events are properly captured on all your systems. Can you post it?
It is a 'feature' of the underlying Win32 API ReadDirectoryChangesW and hence FileSystemWatcher that under heavy load, events can get missed. There are mitigation suggestions in the MSDN docs.
Make sure that you set your watcher:
fileSystemWatcher.EnableRaisingEvents = true;
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.Security.AccessControl;
using System.Security.Permissions;
using System.Text;
using System.Windows.Forms;
namespace Watcher
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
FileRenamed();
}
private static string _osLanguage = null;
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
private void FileRenamed()
{
MessageBox.Show("Code is Started Now");
// Create a new FileSystemWatcher and set its properties.
FileSystemWatcher watcher = new FileSystemWatcher();
SetDirectoryAccess(#"c:\temp");
watcher.Path = #"C:\Temp";
/* Watch for changes in LastAccess and LastWrite times, and
the renaming of files or directories. */
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
// Only watch text files.
watcher.Filter = "*.txt";
// Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
watcher.Error += new ErrorEventHandler(OnError);
// Begin watching.
watcher.EnableRaisingEvents = true;
}
// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e)
{
// Specify what is done when a file is changed, created, or deleted.
//Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
MessageBox.Show("Something is changed in the File");
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
// Specify what is done when a file is renamed.
MessageBox.Show("File Is Renamed");
//WatcherChangeTypes wct = e.ChangeType;
//Console.WriteLine("File {0} {2} to {1}", e.OldFullPath, e.FullPath, wct.ToString());
}
// This method is called when the FileSystemWatcher detects an error.
private static void OnError(object source, ErrorEventArgs e)
{
MessageBox.Show("Error Trapped");
// Show that an error has been detected.
Console.WriteLine("The FileSystemWatcher has detected an error");
// Give more information if the error is due to an internal buffer overflow.
if (e.GetException().GetType() == typeof(InternalBufferOverflowException))
{
// This can happen if Windows is reporting many file system events quickly
// and internal buffer of the FileSystemWatcher is not large enough to handle this
// rate of events. The InternalBufferOverflowException error informs the application
// that some of the file system events are being lost.
Console.WriteLine(("The file system watcher experienced an internal buffer overflow: " + e.GetException().Message));
}
}
private void button1_Click(object sender, EventArgs e)
{
//File.Move(#"\\NAS\dossier_echange\Carl\temp\Test.txt", #"\\NAS\dossier_echange\Carl\temp\Test007.txt");
File.Move(#"c:\temp\Test.txt", #"c:\temp\Test007.txt");
}
internal static void SetDirectoryAccess(string directoryPathString)
{
string everyoneString;
if (OSLanguage.Equals("en-US"))
everyoneString = "Everyone";
else
everyoneString = "Tout le monde";
//sets the directory access permissions for everyone
DirectorySecurity fileSecurity = Directory.GetAccessControl(directoryPathString);
//creates the access rule for directory
fileSecurity.ResetAccessRule(new FileSystemAccessRule(everyoneString, FileSystemRights.FullControl, AccessControlType.Allow));
//sets the access rules for directory
Directory.SetAccessControl(directoryPathString, fileSecurity);
}
public static string OSLanguage
{
get
{
if (_osLanguage == null)
_osLanguage = CultureInfo.CurrentCulture.Name;
return _osLanguage;
}
set
{
_osLanguage = value;
}
}
}
}