I am not very skilled at this void stuff just yet, so any assistance would be appreciated.
First: I am attempting to create a file system watcher, to monitor a directory and if a file is added wait for the file creation to complete, then copy it to another folder. I have pieced together the code below, but I can't figure out how to call the private void watch, to start it up.
Second: does anyone know if it loops on it own? or do I have to create one for it to continue watching the folder?
namespace filewatch
{
class Program
{
public static string watch_path = "C:\\testerson\\";
public static string copy_path = "C:\\copyto\\";
static void Main(string[] args)
{
watch(); <---- how can I call watch from here to start it.
}
public void watch()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = watch_path;
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Filter = "*.*";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}
private void OnChanged(object source, FileSystemEventArgs e)
{
WaitForFile(e.FullPath + e.Name);
System.IO.File.Copy(e.FullPath, copy_path + e.Name);
}
public static bool IsFileReady(string filename)
{
try
{
using (FileStream inputStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None))
return inputStream.Length > 0;
}
catch (Exception)
{
return false;
}
}
public static void WaitForFile(string filename)
{
while (!IsFileReady(filename)) { }
}
}
}
- Edit:
I have changed the private voids to public static, and now no errors arise, but the console app does not stay running. it just starts and stops now. so it's not monitoring the folder.
You should make the watch() method static and simply call it from the Main method.