Network Share Login via C#

Accessing remote share programmatically from Windows is easy. Just use \\machine\share notation and you’re golden. Except if you need to access it with a specific user. While PrincipalContext can often help, for samba shares hosted by Linux, that doesn’t necessarily work.

But we can always use the same thing the Explorer does – WNetUseConnection. And calling upon it is easy enough. We only need to fill NETRESOURCE with a remote path and forward it along as a parameter. Result is standard 0 for success and non-zero for any failure.

Code
bool Login(string path, string user, string password) {
var nr = new NativeMethods.NETRESOURCE {
dwType = NativeMethods.RESOURCETYPE_DISK,
lpRemoteName = path
};
var result = NativeMethods.WNetUseConnection(IntPtr.Zero, nr, password, name, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
return (result == NativeMethods.NO_ERROR);
}

And, of course, we also need our definitions:

Code: NativeMethods
private static class NativeMethods {
internal const Int32 NO_ERROR = 0;
internal const Int32 RESOURCETYPE_DISK = 0x00000001;

[StructLayout(LayoutKind.Sequential)]
internal class NETRESOURCE {
public Int32 dwScope = 0;
public Int32 dwType = 0;
public Int32 dwDisplayType = 0;
public Int32 dwUsage = 0;
public IntPtr lpLocalName;
public String lpRemoteName;
public IntPtr lpComment;
public IntPtr lpProvider;
}

[DllImport("mpr.dll", CharSet = CharSet.Ansi)]
internal static extern Int32 WNetUseConnection(
IntPtr hwndOwner,
NETRESOURCE lpNetResource,
String lpPassword,
String lpUserId,
Int32 dwFlags,
IntPtr lpAccessName,
IntPtr lpBufferSize,
IntPtr lpResult
);

}

And that should be enough for access.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.