@MiPakTeh, Welcome to Microsoft Q&A, based on my test, you could use try catch to ignore the permission error.
Here is a code example you could refer to.
private void OnChanged(object source, FileSystemEventArgs e)
{
try
{
string path = e.FullPath;
if(File.Exists(path))
{
string filename=Path.GetFileNameWithoutExtension(path);
string path1 = Path.Combine(MyPath_2, filename);
Console.WriteLine( path1);
Console.WriteLine( "this is file");
File.Copy(path, path1, true );
}
if(Directory.Exists(path))
{
string directory= new DirectoryInfo(path).Name;
string path2= Path.Combine(MyPath_2, directory);
CopyFilesRecursively(path, path2);
Console.WriteLine( path2);
Console.WriteLine("this is directory");
}
}
catch(Exception ex)
{
Console.WriteLine( ex.Message);
}
}
private void CopyFilesRecursively(string sourceDir, string targetDir)
{
//Now Create all of the directories\
if(!Directory.Exists(targetDir))
{
Directory.CreateDirectory(targetDir);
}
foreach (var file in Directory.GetFiles(sourceDir))
File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file)),true);
foreach (var directory in Directory.GetDirectories(sourceDir))
CopyFilesRecursively(directory, Path.Combine(targetDir, Path.GetFileName(directory)));
}
After using the above code, you could copy the files and directories to the destination folder.
Best Regards,
Jack
If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.