2

I'm accessing other server with the login credentials. My problem is if I run the code initially, it wil show the error as

Logon failure: unknown user name or bad password

but if I try running the code after connecting to the server once through the command prompt. Then, the application works fine and it does not throw any error. So, daily I need to connect to server once through command prompt in order to run the application without errors.

Here is my code:

static void main()
{
  string sourceDir = "//server.domain.mhc//drive";
                string DestinationDir = "D:\\Test";

                DirectoryCopy(sourceDir, DestinationDir, true);
}

[DllImport("advapi32.DLL", SetLastError = true)]
public static extern int LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
    clsEmail objEmail = new clsEmail();
    try
    {
        IntPtr admin_token = default(IntPtr);
        if(LogonUser("myusername","domain","pwd",9,0,ref admin_token) != 0)
        {
            DirectoryInfo dir = new DirectoryInfo(sourceDirName);
            DirectoryInfo[] dirs = dir.GetDirectories();
        }
Picrofo Software
  • 5,475
  • 3
  • 23
  • 37
shakz
  • 629
  • 3
  • 14
  • 38

1 Answers1

6

Found out the solution. See the updated code for the answer.

try
     {
        IntPtr admin_token = default(IntPtr);
        //Added these 3 lines
        WindowsIdentity wid_current = WindowsIdentity.GetCurrent();
        WindowsIdentity wid_admin = null;
        WindowsImpersonationContext wic = null;


        if(LogonUser("myusername","domain","pwd",9,0,ref admin_token) != 0)
        {
        //Newly added lines
         wid_admin = new WindowsIdentity(admin_token);
         wic = wid_admin.Impersonate();

         DirectoryInfo dir = new DirectoryInfo(sourceDirName);
         DirectoryInfo[] dirs = dir.GetDirectories();
         }
     }
shakz
  • 629
  • 3
  • 14
  • 38
  • This code is inside directorycopy() function. Hope this helps for someone. :) – shakz Nov 02 '12 at 06:05
  • 3
    For future readers, make sure you dispose the WindowsIdentity and the ImpersonationContext when finished with them. Either in a finally statement, or better yet to refactor this with some `using` blocks for those resources. – HodlDwon May 13 '14 at 16:50
  • @sachin: I came across same kind of issue to copy files from different domain and it works. – Itz.Irshad Aug 08 '17 at 12:00
  • @HodlDwon: As per [MSDN](https://msdn.microsoft.com/en-us/library/windows/desktop/aa378184(v=vs.85).aspx), LoginUesr will return non-zero if login succeeded. But, in my case whey it returns non-zero value even when user id/pass is provided incorrectly. Anyone know why ? – Itz.Irshad Aug 10 '17 at 06:08