Call Win32 API netapi32.dll to manage UNC (network sharing) connections (I)

Source: Internet
Author: User

This chapter uses Win32 API netapi32.dll to implement UNC connection authorization, disconnect, and obtain the UNC connection status.

1. First import the DLL file:

# Region register Win32 DLL file netapi32.dll // import the connection authorization function netuseadd [dllimport ("netapi32", charset = charset. auto, setlasterror = true), suppressunmanagedcodesecurityattribute] Static extern int netuseadd (string uncservername, // not used int level, // use info struct level 1 or 2 intptr Buf, // buffer ref int parmerror); // The import disconnect function netusedel [dllimport ("netapi32", charset = charset. auto, setlasterror = true), suppressunmanagedcodesecurityattribute] Static extern int netusedel (string uncservername, // not used string usename, // network resource what do you want to disconnect; uint forcecond // disconnect mode;); // import the get connection status function netusegetinfo [dllimport ("netapi32", charset = charset. auto, setlasterror = true), suppressunmanagedcodesecurityattribute] Static extern int netusegetinfo (string uncservername, string usename, int level, ref intptr bufptr); <PRE> </PRE>

The code written for C # has been converted to the parameter Type above. For more information about function prototypes, see msdn,

Next, I will give a brief introduction to the above parameters, which is sufficient for the content described in this chapter (for more details, see msdn ):

(In ascending order)

String uncservername:

This parameter is not required and is left empty during call.

Int level:

Indicates the type of struct used to pass the parameter into the function. 1 indicatesUse_info_1Or 2 standsUse_info_2, Smart choose between the two.

Intptr Buf,

A pointer pointing to the corresponding structure above (C # has no pointer, but this function is very similar to a pointer. A friend who knows more professional teaching methods will give a notice ),

Ref int parmerror:

This seems to be useless, so I did not study it carefully. Please check the usage in sourcecode.

Uint forcecond:

There are three modes for disconnecting:

Private const uint use_noforce = 0; // do not fail the disconnection if open files exist son the connection.
Private const uint use_force = 1; // fail the disconnection if open files exists on the connection.
Private const uint use_lots_of_force = 2; // close any open files and delete the connection.

Ref intptr bufptr:

The struct intprt object that is passed in to getnetuseinfo to bring the obtained information out.

 

To implement the complete source code of the three functions:

 

Class winnet {# region define netapi32.dll need data structure [structlayout (layoutkind. sequential, charset = charset. auto)] public struct _ use_info_2 {internal string ui2_local; internal string ui2_remote; // internal intptr ui2_password; // don't pass a string or stringbuilder here !! Internal string ui2_password; internal uint ui2_status; internal uint timeout; internal uint ui2_usecount; internal string ui2_username; internal string timeout;} const uint use_wildcard = 0 timeout; private const uint use_noforce = 0; // do not fail the disconnection if open files exist son the connection. private const uint use_force = 1; // fail the disconnection if open files exists on the connection. private const uint use_lots_of_force = 2; // close any open files and delete the connection. private const uint use_ OK = 0; // The connection is valid. private const uint use_paused = 1; // paused by local workstation. private const uint use_sesslost = 2; // disconnected. private const uint use_disconn = 3; // an error occurred. private const uint use_neterr = 4; // a network error occurred. private const uint use_conn = 5; // The connection is being made. private const uint use_reconn = 6; // reconnecting. private Static winnet _ instance = new winnet (); public static winnet instance {get {return _ instance; }}# endregion # region register Win32 DLL file netapi32.dll [dllimport ("netapi32 ", charset = charset. auto, setlasterror = true), suppressunmanagedcodesecurityattribute] Static extern int netuseadd (string uncservername, // not used int level, // use info struct level 1 or 2 intptr Buf, // buffer ref int parmerror); [dllimport ("netapi32", charset = charset. auto, setlasterror = true), suppressunmanagedcodesecurityattribute] Static extern int netusedel (string uncservername, // not used string usename, // network resource what do you want to disconnect; uint forcecond // disconnect mode;); [dllimport ("netapi32", charset = charset. auto, setlasterror = true), suppressunmanagedcodesecurityattribute] Static extern int netusegetinfo (string uncservername, string usename, int level, ref intptr bufptr); # endregion ////// Establish a use record ///////////////Public static bool userecord (string resource, string user, string password, string domain) {bool rtnvalue = false; int ret = 1; int paramerror = 0; _ use_info_2 use2 = new _ use_info_2 (); intptr pbuf = intptr. zero; // use2.ui2 _ password = intptr. zero; try {pbuf = marshal. allochglobal (marshal. sizeof (use2); use2.ui2 _ local = NULL; use2.ui2 _ asg_type = use_wildcard; use2.ui2 _ remote = resource; // use2.ui2 _ Password = marshal. stringtohglobalauto (password); use2.ui2 _ password = password; use2.ui2 _ username = user; use2.ui2 _ domainname = domain; marshal. structuretoptr (use2, pbuf, true); ret = netuseadd (null, 2, pbuf, ref paramerror); If (Ret! = 0) {Throw new exception (errorcodehandler (RET);} rtnvalue = true;} catch (exception e) {Throw E;} finally {marshal. freehglobal (pbuf);} return rtnvalue ;}////// Destroy a use record //////Public static void deleterecord (string resource) {int ret = 1; try {ret = netusedel (null, resource, use_lots_of_force); If (Ret! = 0) {Throw new exception (errorcodehandler (RET) ;}} catch (exception e) {Throw e ;}public static _ use_info_2 getuseinfo (string resource) {int ret = 1; _ use_info_2 ui2 = new _ use_info_2 (); intptr pbuf = intptr. zero; try {pbuf = marshal. allochglobal (marshal. sizeof (New _ use_info_2 (); ret = netusegetinfo (null, resource, 2, ref pbuf); If (Ret! = 0) {Throw new exception (errorcodehandler (RET);} ui2 = (_ use_info_2) Marshal. ptrtostructure (pbuf, typeof (_ use_info_2);} catch {// throw E;} finally {marshal. freehglobal (pbuf);} return ui2;} # region Win32 errorcode handler code public static string errorcodehandler (INT win32errorcode) {string rtnmessage = string. empty; Switch (win32errorcode) {Case 67: rtnmessage = "network name not found. "; break; Case 1219: rtnmessage = "a user cannot use more than one user name to connect to a server or shared resource. Disconnect all connections to this server or shared resource, and try again... "; break; Case 2250: rtnmessage =" this network connection does not exist. "; break; default: rtnmessage =" unkown error code. "; break;} return rtnmessage +"/R/nwin32 Error Code: "+ win32errorcode;} # endregion}

 

 

The exception handling of API calls is also a bug I encountered when debugging code. By the way, I would like to share with you the following:

Generally, when an API call encounters an exception, the getlasterror () method is used to obtain the last error, and n (n> 10) errors occur during actual execution, the error message obtained using getlasterror () is "overlapping I/O operations in progress". No answer is obtained for help, later, I found that after each API ends, a return value of the int type is returned: 0 indicates that the execution is successful. In this chapter, the commonly used errorcodehandler () method is described.

 

Next, if you are free, plan to write a Windows UNC shared management applet, which will involve listing all the current sharing statuses and all sharing operations.

 

Remark:

Currently, only the connection or disconnection status can be determined when the above information is obtained. Therefore, only these two statuses are required for my project, so no detailed classification is performed.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.