Connect to a netword share via UNC name

G

Gaetano D'Aquila

Hi,
There is anyone that have a piece of C# code that show how to use
Directory.GetDirectories() over a UNC path?
Example:
I need to use Directory.GetDirectories(\\server\resource)
I need to Impersonate "on-the-fly" an user before the call to
Directory.GetDirectories and then restore the old account.
Now I use this (at the end of e-mail) attached class to handle
Impersonification, then I use

CImpersonification i=new CImpersonification()
if i.impersonate("username","password","domain")
Directory.GetDirectories(\\\\server\\resource)

But not work.
Anyone can help me?
Thank you.

===================== START HERE ========================================
using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;

namespace test
{
public class CImpersonation
{
private WindowsIdentity newidentity;
private WindowsImpersonationContext impcontext;

// Declare the logon types as constants
const long LOGON32_LOGON_INTERACTIVE = 2;
const long LOGON32_LOGON_NETWORK = 3;

// Declare the logon providers as constants
const long LOGON32_PROVIDER_DEFAULT = 0;
const long LOGON32_PROVIDER_WINNT50 = 3;
const long LOGON32_PROVIDER_WINNT40 = 2;
const long LOGON32_PROVIDER_WINNT35 = 1;

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

public bool impersonate(
string Username,
string Password,
string Domain)
{
// This is the token returned by the API call
// Look forward to a future article covering
// the uses of it
IntPtr token = new IntPtr(0);
token = IntPtr.Zero;

// Call the API
if (LogonUser(
Username,
Domain,
Password,
(int)LOGON32_LOGON_NETWORK,
(int)LOGON32_PROVIDER_DEFAULT,
ref token))
{
//' Since the API returned TRUE, return TRUE to the caller
newidentity = WindowsIdentity.GetCurrent();
impcontext = WindowsIdentity.Impersonate(token);
return true;
}
else
{
//' Bad credentials, return FALSE
return false ;
}
}

public void revertimpersonation()
{
impcontext.Undo();
//newidentity = Nothing;
}
}
}


===================== STOP HERE ==========================================
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top