1

I have written a C# console app that will copy a backup from one server to another on a schedule every day. This works perfectly if I have logged into the share folder and my credentials are chached, however if my credentials have not been input on the share of the source server, I get an error in my code. What I need to do is have my app impersonate a login to my shared folder of the source, so I can grab the file and move it to its destination.

public static void CopyNewestBackup()
        {

        string sourcePath = @"\\source";
        string targetPath = @"\\destination";

        FileInfo newestFile = GetNewestFile();
        string sourceFile = Path.Combine(sourcePath, newestFile.Name);
        string destFile = Path.Combine(targetPath, newestFile.Name);
        Console.Write("Copying " + newestFile.Name + " from " + sourcePath + " to " + destFile);

        FileSystem.CopyFile(sourceFile, destFile, UIOption.AllDialogs);
        //File.Copy(sourceFile, destFile, true);
    }

How can I impersonate a login to the server to grab the file?

EvanGWatkins
  • 1,427
  • 6
  • 23
  • 52
  • Are you running the Console App from your machine ..? or do you have this running on an actual server that will copy the files over to the Target Server..? you should not use impersonation you should create a service account on the Target Machine and use those NetWork Credentials in your Application where you are running the Console App – MethodMan Feb 08 '13 at 13:24
  • @DJKRAZE it is running on my machine, not on the server – EvanGWatkins Feb 08 '13 at 13:25
  • Well there you have it.. ! you should still be able to run that if your network credentials are valid on the target machine.. why would you want to use Impersonation ..looking at your code I wonder if you combining the paths correctly can you show what the path looks like in the debugger.. – MethodMan Feb 08 '13 at 13:28
  • @DJKRAZE the paths are fine, I can log into the share and then run the app on my machine and it works fine, trying to eliminate having to log into the share everyday. When I run the code it tells me the source can not be accessed. If I log into the share manually and run the application it copies the file fine. – EvanGWatkins Feb 08 '13 at 13:29
  • I understand now .. I wonder if you need to pass in the network Credentials in your code behind which I can't tell based on the code.. but Impersonation for what you are doing should work.. you could convert that console to Consume a `Windows Service` and you wouldn't have to do what you are doing manually all the time.. here is a good example on StackOverflow http://stackoverflow.com/questions/5146155/how-to-create-c-sharp-console-application-to-cosume-the-net-webservice – MethodMan Feb 08 '13 at 13:33

1 Answers1

1

This MSDN article gives a good view on impersonation: http://msdn.microsoft.com/en-us/library/chf6fbt4.aspx

Richard Barker
  • 1,161
  • 2
  • 12
  • 30
VoonArt
  • 884
  • 1
  • 7
  • 21