سؤال

This code works fine with me:

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

    [DllImport("kernel32.dll")]
    public static extern bool CloseHandle(IntPtr token);

enum LogonType
    {
        Interactive = 2,
        Network = 3,
        Batch = 4,
        Service = 5,
        Unlock = 7,
        NetworkClearText = 8,
        NewCredentials = 9
    }
    enum LogonProvider
    {
        Default = 0,
        WinNT35 = 1,
        WinNT40 = 2,
        WinNT50 = 3
    }

private void Button1_Click()
    { 
        IntPtr token = IntPtr.Zero;
        LogonUser("Administrator",
                  "192.168.1.244",
                  "PassWord",
                  (int)LogonType.NewCredentials,
                  (int)LogonProvider.WinNT50,
                  ref token);
        using (WindowsImpersonationContext context = WindowsIdentity.Impersonate(token))
        {
    CloseHandle(token);
    /*
    Code_of_Do_Something
    */
    }
}

BUT...This means I have to repeat the last code which inside "Button1_Click()" each time I need to do impersonation ( Doing something on the remote machine = server). So my question: Is it possible to do something like this illustration?: enter image description here

هل كانت مفيدة؟

المحلول 2

Yes, it is possible to pass code as a parameter. But let's solve your problem without using lambdas:

private void Button1_Click()
{
    using(GetImpersonationContext())
    {
        /* code here */
    } 
}
private WindowsImpersonationContext GetImpersonationContext()
{
    IntPtr token = IntPtr.Zero;
    LogonUser("Administrator",
              "192.168.1.244",
              "PassWord",
              (int)LogonType.NewCredentials,
              (int)LogonProvider.WinNT50,
              ref token);

    WindowsImpersonationContext context = WindowsIdentity.Impersonate(token);
    CloseHandle(token);
    return context;
}

نصائح أخرى

You can use delegates for this purpose. The easiest way is to use Action or Func. If you don't need a return value, use an Action:

private void RunImpersonated(Action act)
{
    IntPtr token = IntPtr.Zero;
    LogonUser("Administrator",
              "192.168.1.244",
              "PassWord",
              (int)LogonType.NewCredentials,
              (int)LogonProvider.WinNT50,
              ref token);
    try
    {
        using (WindowsImpersonationContext context = WindowsIdentity.Impersonate(token))
        {
            // Call action
            act();
        }
    }
    finally
    {
        CloseHandle(token);
    }
}

Note that there are lots of variations with generic type parameters that allow you to also provide parameters to Action or Func delegates in a strongly typed way. If you need an into parameter for instance, use Action<int> instead of just Action.

Also note that I created a finally block that closes the handle whether an exception occurs or not.

In order to call the function, you can use a lambda expression:

private void button1_Click(object sender, EventArgs e)
{
    RunImpersonated(() => {
        DirectoryInfo dir = new DirectoryInfo( @"\\192.168.1.244\repository");
        foreach (DirectoryInfo di in dir.GetDirectories()) 
        { 
            lable_folders_count.Text = Convert.ToString(dir.GetFileSystemInfos().Length); 
        }
    });
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top