You can use delegates for this purpose. The easiest way is to use Action or Func . If you do not need a return value, use 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)) {
Note that there are many variations of generic type parameters that allow you to also provide parameters to Action or Func delegates in a strongly typed way. If you need the in parameter, use an Action<int> instead of an Action .
Also note that I created a finally block that closes the descriptor if an exception is thrown.
To call a function, you can use the 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); } }); }
source share