tags:

views:

94

answers:

4

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.

A: 

you can use system.diagnostocs.process to call out to 'net use .... with userid and password' or to a command shell that takes those.

Preet Sangha
You can, but would you want to?
Steve Townsend
Why not if it achieves the aim of your use case then it's completely valid. Its one line of code that achieves the desired result. It's got all of the error handling built in, and is tried an tested. Seems silly to rewrite the functionality.
Preet Sangha
"if it achieves the aim of your use case then it's completely valid" - that's a very sweeping statement, and your answer here is a counterexample in my opinion. Starting up a new process to do something that can be done in a single P/Invoke (no rewrite required) is using a sledgehammer to crack a nut.
Steve Townsend
+1  A: 

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
        );

Example code here.

Brian R. Bondy
A: 

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
}
bzlm
Only works well in a Windows environment. When you start going to AS400, Solaris and Linux it becomes troublesome, especially if the shares requires a credential other than the one your are running the application under.
Riaan
+1  A: 

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

Riaan