Click here to Skip to main content
11,577,643 members (22,060 online)
Click here to Skip to main content

Connect to a UNC Path with Credentials

, 16 Oct 2009 CPOL 129K 12.5K 74
Rate this:
Please Sign up or sign in to vote.
Use NetApi32 to establish and break connections to UNC paths using specified user credentials.

Connection.jpg

Introduction

This article demonstrates how you can connect to a remote resource via a UNC path and pass user credentials. It implements the IDisposable interface so you can use it within a using() block.

Background

I had an ASP.NET site where I wanted to access network resources, but did not have sufficient share permissions because the code ran under the ASP user. I also had a service that copied files every night between file shares in two different domains. I wanted a way to access remote resources without opening up security holes by changing permissions or running as a privileged user.

Using the code

The UNCAccessWithCredentials class implements the Win32 methods NetUseAdd() and NetUseDel() to create the remote connections. Connections added with NetUseAdd are not visible in Explorer. When active, they will show via the DOS Net Use command.

The class also implements the IDisposable interface so that we can use a using() block. Once the end of the block is reached, the class automatically disconnects the UNC connection in its Dispose() methods.

using (UNCAccessWithCredentials unc = new UNCAccessWithCredentials())
{
    if (unc.NetUseWithCredentials(uncpath, user, domain, password))
    {
        // Insert your code that requires access to the UNC resource
    }
    else
    {
        // The connection has failed. Use the LastError to get the system error code
        MessageBox.Show("Failed to connect to " + tbUNCPath.Text + 
                        "\r\nLastError = " + unc.LastError.ToString(),
                        "Failed to connect",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
    }
// When it reaches the end of the using block, the class deletes the connection.
}

If you require persistent connections, declare an instance of the class and use the NetUseWithCredentials() method to connect. Once connected, you can access the remote resource at need until disconnected. Do not forget to remove the connection when you are finished using the NetUseDelete() method..

Interpreting Errors

Error.jpg

If the methods fail, they return false. If this occurs, use the class' LastError property to obtain the Windows System Error Code. You can use the MSDN System Error Codes page to obtain a description of the error.

In the error above, Error 53 is ERROR_BAD_NETPATH - "The network path was not found". It looks like I specified the wrong server or share path.

Points of Interest

In researching how to do this task, I found many interesting hacks that got the job done but were not savory. Some used the LogonUser() method, which only works if your remote user has logon rights on the executing machine. I also found cases where the programmer ran a shell net use command.

Using the API NetUseAdd method, we can control the process within code, without having to hack permissions or resort to DOS commands.

I could not find a way to do this in managed code. If you know of one, please post your solution. I would love to see it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

hayes.adrian
Systems Engineer ThomsonReuters Tax & Accounting
United States United States
I am a Senior System Administrator for a 400+ server ASP farm. With such a large farm and limited staff, our goal is to add as much automation as possible to the system. Most of my programming consists of intelligent slack: spending 2 hours to write a program that handles a reoccurring 10 minute manual job.

You may also be interested in...

Comments and Discussions

 
GeneralGreat one works very much. Pin
Anmol.Gupta15-Apr-15 20:35
memberAnmol.Gupta15-Apr-15 20:35 
QuestionHow run it from windows service Pin
kalatjosef3-Mar-15 5:40
memberkalatjosef3-Mar-15 5:40 
QuestionVery helpful Pin
Derrick Roach30-Jan-15 6:02
memberDerrick Roach30-Jan-15 6:02 
QuestionBeautiful Pin
Nicolai Kjaersgaard3-Dec-14 13:48
memberNicolai Kjaersgaard3-Dec-14 13:48 
GeneralWork Great! Much Thanks. Pin
Chuck Bevitt15-Oct-14 12:58
memberChuck Bevitt15-Oct-14 12:58 
GeneralMy vote of 4 Pin
Frank Sandersen3-Sep-14 2:08
memberFrank Sandersen3-Sep-14 2:08 
GeneralMy vote of 3 Pin
Member 1097649828-Jul-14 10:28
memberMember 1097649828-Jul-14 10:28 
SuggestionWorked, however wasn't clear... Pin
Member 1097649828-Jul-14 10:25
memberMember 1097649828-Jul-14 10:25 
BugOnly Deletes Last Attached Share Pin
Member 1091457430-Jun-14 5:56
memberMember 1091457430-Jun-14 5:56 
QuestionIs it possible to pass the credentials of the current user's security context? Pin
Member 46054763-Feb-14 4:26
memberMember 46054763-Feb-14 4:26 
AnswerRe: Is it possible to pass the credentials of the current user's security context? Pin
hayes.adrian9-Apr-14 14:24
memberhayes.adrian9-Apr-14 14:24 
GeneralMy vote of 4 Pin
hamzemirhosseini31-Jul-13 23:08
memberhamzemirhosseini31-Jul-13 23:08 
QuestionExample of mydomain.local? Pin
hueikar25-Jul-13 22:46
memberhueikar25-Jul-13 22:46 
QuestionNice Pin
emces14-Feb-13 0:57
memberemces14-Feb-13 0:57 
GeneralMy vote of 5 Pin
kkkkkkkkkkkkkkkkkkkkkkkkk20-Sep-12 21:05
memberkkkkkkkkkkkkkkkkkkkkkkkkk20-Sep-12 21:05 
QuestionParallel Execution Pin
puromtec122-Aug-12 8:12
memberpuromtec122-Aug-12 8:12 
AnswerRe: Parallel Execution Pin
hayes.adrian22-Aug-12 10:48
memberhayes.adrian22-Aug-12 10:48 
GeneralRe: Parallel Execution Pin
puromtec122-Aug-12 10:49
memberpuromtec122-Aug-12 10:49 
AnswerRe: Parallel Execution Pin
puromtec122-Aug-12 10:48
memberpuromtec122-Aug-12 10:48 
GeneralRe: Parallel Execution Pin
hayes.adrian23-Aug-12 6:27
memberhayes.adrian23-Aug-12 6:27 
AnswerRe: Parallel Execution Pin
Ronald Reynolds29-Apr-14 12:26
memberRonald Reynolds29-Apr-14 12:26 
QuestionSimply Works Pin
jon-e1-Aug-12 4:23
memberjon-e1-Aug-12 4:23 
QuestionHow to give UNC path? Pin
DRKARTHIKRAJ18-Jun-12 0:00
memberDRKARTHIKRAJ18-Jun-12 0:00 
AnswerRe: How to give UNC path? Pin
hayes.adrian17-Jul-12 6:59
memberhayes.adrian17-Jul-12 6:59 
GeneralRe: How to give UNC path? Pin
DRKARTHIKRAJ1-Aug-12 1:49
memberDRKARTHIKRAJ1-Aug-12 1:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150603.1 | Last Updated 16 Oct 2009
Article Copyright 2009 by hayes.adrian
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid