Reputation: 43
I've created a window service application where it read files from other networks then save it to my database every 1 minute. I have been provided a username and password to access the file from the other network. Unfortunately, I don't know how to how to access the file with network username and. password Can you show me how. Thank you.
I know how to provide the path of the file from app.config
appSettings
add key="filepath" value="\111.111.1.11\dummyfolder\"
And access it to my code by this:
string path = ConfigurationManager.AppSettings["filepath"].ToString();
Upvotes: 0
Views: 342
Reputation:
What can be easier?
class AuthHelper
{
public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_PROVIDER_DEFAULT = 0;
[DllImport("advapi32.dll")]
public static extern int LogonUserA(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool RevertToSelf();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);
public static WindowsIdentity GetWindowsIdentityForUser(String userName, String password, String domain)
{
WindowsIdentity result = null;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (RevertToSelf())
if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0)
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
result = new WindowsIdentity(tokenDuplicate);
if (result != null) return result;
}
if (token != IntPtr.Zero) CloseHandle(token);
if (tokenDuplicate != IntPtr.Zero) CloseHandle(tokenDuplicate);
return result;
}
}
And then just:
var identity = AuthHelper.GetWindowsIdentityForUser("other user", "password", "domain");
using (var context = identity.Impersonate())
{
//do whatever you want as "other user"
}
Upvotes: 0