0

I want to copy a file to a Shared folder. I can manually copy the file but I want to schedule it to run every hour.

First I made a batch file:

xcopy "D:\DATA\file.bak" "\\SharedFolder\DATA\"

It shows that the file has been copied, but there is nothing in the Shared folder.

Next I tried to use File.Copy but it didn't work as expected. I find that I need to have a User Identity for this.

So, here is my code:

AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
IntPtr user = IntPtr.Zero;
bool loggedon = LogonUser(
"User", //Username
"Domain", //Domain
"", // Password
2, // interactive
0, // default
out user);
if (loggedon)
{
  using (WindowsIdentity.Impersonate(user))
  {
    File.Copy(Sourcepath, DestPath, true);
    MessageBox.Show("Done");
  }
}
else
{
  MessageBox.Show("Failed");
}

But this account doesn't have a password so I don't know what to put in the password field.

Is there another way to impersonate the current logged in user? Or do I need to make a password?

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
  • This might help you https://stackoverflow.com/questions/8304398/is-it-possible-for-a-windows-service-impersonate-a-user-without-a-password – barianos Jun 23 '20 at 06:52
  • There's no need for impersonation or using passwords if you use eg Windows' Scheduled Tasks. You can specify that the job will run using a specific user's credentials. Perhaps the question you should as is how to run your job using a specific user with whatever job scheduler you use? – Panagiotis Kanavos Jun 23 '20 at 08:31
  • @panagiotis_kanavos I did not know that Windows' Scheduled Tasks allow running program using specific user. That sound like exactly what I need. – Tran Dai Phuc Jun 23 '20 at 08:56

0 Answers0