Access to shared folders on network which credential authentication required

The advantage of this method is that you can login to any shared resource regardless same domain or not. You will not also need to impersonate to any account. All you need is just to put this code in (C# language) into the top of your class, then enjoy it 🙂

        privatestaticexternint WNetAddConnection2A(refNetResource pstNetRes, string psPassword, string psUsername, int piFlags);
        privatestaticexternint WNetCancelConnection2A(string psName, int piFlags, int pfForce);
        publicint iScope;
        publicint iType;
        publicint iDisplayType;
        publicint iUsage;
        publicstring sLocalName;
        publicstring sRemoteName;
        publicstring sComment;
        publicstring sProvider;
        privateconstint RESOURCETYPE_DISK = 0x1;
    privatevoid LoginToShare(string serverName, string shareName, string user, string password) {
        string destinationDirectory = string.Format(@"\\{0}\{1}", serverName, shareName);
        NetResource nr = newNetResource();
        nr.iScope = 2;
        nr.iType = RESOURCETYPE_DISK;
        nr.iDisplayType = 3;
        nr.iUsage = 1;
        nr.sRemoteName = destinationDirectory;
        nr.sLocalName = null;

        int flags = 0;
        int rc = WNetAddConnection2A(ref nr, password, user, flags);
        if (rc != 0) thrownewWin32Exception(rc);

    privatevoid LogoutFromShare(string serverName, string shareName)
        string destinationDirectory = string.Format(@"\\{0}\{1}", serverName, shareName);
        int flags = 0;
        int rc = WNetCancelConnection2A(destinationDirectory, flags, Convert.ToInt32(false));

There’re two function you can use, first use:


to log in to the shared resource. If the verification is successul, then you can access to resource by path as without verification or you will get an error message like wrong username/password.

Once your work done, call


to disconnect from resource.


About Trung Ninh

A man on the road to become a millionaire
This entry was posted in .NET, Programming tips and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s