How do I supply credential so that I can connect to a network drive in .NET?
I’m trying to retrieve files from a network drive and need to supply user credentials to access the drive.
How do I supply credential so that I can connect to a network drive in .NET?
I’m trying to retrieve files from a network drive and need to supply user credentials to access the drive.
you can use system.diagnostocs.process to call out to 'net use .... with userid and password' or to a command shell that takes those.
The best way to do this is to p/invoke WNetUseConnection.
[StructLayout(LayoutKind.Sequential)]
private class NETRESOURCE
{
public int dwScope = 0;
public int dwType = 0;
public int dwDisplayType = 0;
public int dwUsage = 0;
public string lpLocalName = "";
public string lpRemoteName = "";
public string lpComment = "";
public string lpProvider = "";
}
[DllImport("Mpr.dll")]
private static extern int WNetUseConnection(
IntPtr hwndOwner,
NETRESOURCE lpNetResource,
string lpPassword,
string lpUserID,
int dwFlags,
string lpAccessName,
string lpBufferSize,
string lpResult
);
You can use the WindowsIdentity class (with a logon token) to impersonate while reading and writing files.
var windowsIdentity = new WindowsIdentity(logonToken);
using (var impersonationContext = windowsIdentity.Impersonate()) {
// Connect, read, write
}
A constant pain in the *, since I need to connect to AS/400, Linux and Solaris network shares over and above Windows ones.
I'm using one of the Win32 API wrappers. Specifically this class that takes care of most of the 'plumbing'.
Check out the Code Project article: Connect to a UNC Path with Credentials