I am trying to make a watcher to make every file sent to a shared folder of which I have read and write permissions, to summarize I have administrator permissions.
What I want to achieve is that every time a file is sent to that folder, copy this file to a folder on my computer "Locally" and after having this copy delete the file that is in the shared folder, I was seeing methods and use them and everything worked fine but then they asked me to change the address of the destination folder and the source folder of the file, when I was in the test of this part when I changed the destination or origin folder ok but if I change the 2 it tells me the following:
System.UnauthorizedAccessException: 'Access to the path' \ MXD6C4Y7M2 \ Users \ dmontane \ Desktop \ test2 \ paco.xml 'is denied.'
This error sometimes occurs with the File.Copy or with the File.Delete and the error is mine because the watcher I feel is poorly implemented please help this is the code:
The value of the pathr is the external folder and the value of path2 is the internal folder and if after doing the copy it is sent to delete but I do not know how to ask it to ask if the copy was satisfactory and then delete it.
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public static void Run()
{
string[] args = System.Environment.GetCommandLineArgs();
FileSystemWatcher watcher = new FileSystemWatcher();
FileSystemWatcher watcher2 = new FileSystemWatcher();
try
{
watcher.Path = pathr;
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Filter = "*.xml*";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}
catch (Exception e)
{
MessageBox.Show("Error "+e.Message);
}
try
{
watcher2.Path = path2;
watcher2.NotifyFilter = NotifyFilters.LastWrite;
watcher2.Filter = "*.xml*";
watcher2.Changed += new FileSystemEventHandler(LocalChange);
watcher2.EnableRaisingEvents = true;
}
catch (Exception e)
{
MessageBox.Show("Error " + e.Message);
}
}
// -----------------------------------------Define the event handlers---------------------------------------------------------------------------------------
private static void OnChanged(object source, FileSystemEventArgs e)
{
//especifica que se hace cuando un archivo se cambia crea o se borra
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
sourceFile = Path.Combine(pathr, fileName);
destFile = Path.Combine(path2, fileName);
if (!Directory.Exists(path2))
{
Directory.CreateDirectory(path2);
}
try
{
File.Copy(sourceFile, destFile, true);
}
catch(IOException ex)
{
}
cambio = true;
}
private static void LocalChange(object source, FileSystemEventArgs e)
{
//especifica que se hace cuando un archivo se cambia crea o se borra
sourceFile = Path.Combine(pathr, fileName);
destFile = Path.Combine(path2, fileName);
if (File.Exists(sourceFile))
{
try
{
File.Delete(sourceFile);
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
}
cambio = true;
}