I want a program that will constantly monitor a folder for files, when a file appears in said folder the program should wait for the file to be accessible and then move said file to another folder. Currently the files are not being moved from folder "test" to "test2".
I made it so that when i click the start button the form is minimized and runs in background constantly monitoring the folder.
private void btstart_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"C:\test";
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Created += new FileSystemEventHandler(watcher_FileCreated);
watcher.EnableRaisingEvents = true;
}
public static bool Ready(string filename)
{
try
{
using (FileStream inputStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None))
return inputStream.Length > 0;
}
catch (Exception)
{
return false;
}
}
void watcher_FileCreated(object sender, FileSystemEventArgs e)
{
string path1 = @"C:\test";
string path2 = @"C:\test2";
string files = @"*.*";
string[] fileList = Directory.GetFiles(path1, files);
foreach (string file in fileList)
{
if (Ready(file) == true)
{
File.Move(path1, path2);
}
}
}
Apperently it is not obvious, but what is happening is that the file is not moved from folder "test" to folder "test2", there is no exception thrown, there are no errors, the file is not in use by anything nor is it open, permissions are all set correctly aswell, the file is simple not being moved
EDIT SOLUTION : The code works now thanks to the answer posted in this thread. Ive added a couple of things myself so that a duplicate exception will be handled.
folderlocationpath & folderdestinationpath variables are read through a folderbrowserdialog, so that user can choose the 2 folder locations himself This is what i currently have :
string path1 = folderlocationpath;
string path2 = folderdestinationpath;
string files = @"*.*";
string[] fileList = Directory.GetFiles(path1, files);
foreach (string file in fileList)
{
if (Ready(file) == true)
try
{
File.Move(file, Path.Combine(path2, Path.GetFileName(file)));
}
catch (IOException) // for duplicate files an exception that deletes the file in destination folder and then moves the file from origin folder
{
string files2 = Path.GetFileName(file);
string[] fileList2 = Directory.GetFiles(path2, files2);
foreach (string file2 in fileList2)
File.Delete(file2);
File.Move(file, Path.Combine(path2, Path.GetFileName(file)));
}
}