Use network functions in C # (Part one user function) [Translate]

Source: Internet
Author: User
Tags functions network function requires win32
function | Network This article will focus on the functions involved in network management in the Win32 API library. First of all, I'd like to say a few words on. NET Framework, the first of these is the Active Directory method, which requires you to install Active Directory. Two methods for managing users. If you plan to manage a user on a small network, or a stand-alone workstation that does not have Active Directory installed, it may not be worthwhile to install Active Directory to manage users. Another approach is what this article is about--using the Win32 API library function. In this article, I'll explain how to use C # to add, remove, and modify users and groups, and how to query the user and network information for a host or network. We'll use the following functions
    • NetUserAdd
    • Netuserdel
    • NetUserGetInfo
    • NetUserSetInfo
    • NetUserChangePassword
    • Netuserenum
    • netusergetlocalgroups

Class

First, as many C # developers know, we're going to introduce InteropServices namespaces into our projects so that we can access the functions in the DLL. This can be achieved by using the following code fragment:

/////Code Snippets 1.0

using System.Runtime.InteropServices;

////code End

Once we have access, we can introduce the function declarations in the DLL, and we will use methods and structs to correlate them. The function call is discussed below:

add a user using C #

One of the most important operations in a network function is to add a user to a network or computer. To add a user through C #, we need to use the Netadduser function, which allows us to add users to a particular computer, and if we empty the ServerName, the user will be added to the local computer. In the following code snippet, we'll see how to declare and use the NetUserAdd function. Before we can use this function, we need to define a struct body user_info_1 as a netuseradd parameter.

/////Code Snippet 1.1 statement

[DllImport ("Netapi32.dll")]
extern static int NetUserAdd ([MarshalAs (UNMANAGEDTYPE.LPWSTR)] string servername, int level, ref user_info_1 buf, int parm _ERR); ////Code End

When working with code, you should note that one o'clock-although you use the last int parameter, you do not need to know the error value returned. If you must understand the error, you need to modify the code. Now that we have declared the external API we want to use, we should declare the structure.
/**//////code fragment 1.2 Structural body Declaration

[StructLayout (layoutkind.sequential, CharSet = CharSet.Unicode)]
public struct
User_info_1
{
public string
Usri1_name;
public string
Usri1_password;
public int
Usri1_password_age;
public int
Usri1_priv;
public string
Usri1_home_dir;
public string
comment;
public int
Usri1_flags;
public string
Usri1_script_path;
}


/**/
/// /End of code

after the declaration, we can call the function in our program. Here's how to use the code for NetUserAdd:
/**//////Code Snippet 1.3 NetUserAdd

User_info_1 NewUser = new User_info_1 (); Create an new instance of the User_info_1 struct

Newuser.usri1_name = "Usertestone"; Allocates the username
Newuser.usri1_password = "password"; Allocates the password
Newuser.usri1_priv = 1; Sets the account type to User_priv_user
Newuser.usri1_home_dir = null; We didn ' t supply a home Directory
Newuser.comment = "My Made through C #"; Comment on the User
Newuser.usri1_script_path = null; We didn ' t supply a Logon Script Path

if (NetUserAdd (null, 1, ref newuser, 0)!=0)//If the call fails we get a Non-zero value
{
MessageBox.Show ("Error adding User", "error", Messageboxbuttons.ok,messageboxicon.error);
}
/**/////Code End


The code above will add users to the current local computer, but as I said, if you want to add users to another computer on the network, you can replace the null in the first argument with the name of that computer.

To delete a user using C #


It is much simpler to delete a user's function than the previous function. In the above code, if the add user fails, a value of 0 is returned. As with the code above, deleting a user function is also true. To remove a user from your local computer, you can use the following code snippet.
/**//////Code Snippet 1.4 statement

[DllImport ("Netapi32.dll")]
extern static int Netuserdel ([MarshalAs (UNMANAGEDTYPE.LPWSTR)] string servername, [MarshalAs (UNMANAGEDTYPE.LPWSTR)] string username);

/**/////Code End
The calling code for the Netuserdel is as follows:
/**//////Code Snippet 1.5 Netuserdel

if (Netuserdel (null, "Usertestone")!=0)//If the call fails we get a Non-zero value
{
MessageBox.Show ("Error removing User", "error", Messageboxbuttons.ok,messageboxicon.error);
}

/**/////Code End

As with NetUserAdd calls, if you want to remove a user on a remote computer, you need to replace the first parameter with the remote computer name.

use C # to obtain and modify user information

To get user information in C #, we need to call NetUserGetInfo, which uses a struct to manage the data, and the user information is returned to the structure. The function associated with NetUserGetInfo is NetUserSetInfo, which you can use to modify the user information you obtain. It's important to note that these two functions are interdependent, such as using the NetUserSetInfo function, you must know the user's permission levels (privilege level), and the permission levels are obtained by the NetUserGetInfo function. In the following code snippet, we'll see the declarations of these two functions, and we'll use the user_info_1 structure again.

/**//////Code Snippet 1.6 statement

[DllImport ("Netapi32.dll")]
extern static int NetUserGetInfo ([MarshalAs (UNMANAGEDTYPE.LPWSTR)] string Servername,[marshalas ( UNMANAGEDTYPE.LPWSTR)] string username,int level,out IntPtr bufptr);

[DllImport ("Netapi32.dll")]
extern static int NetUserSetInfo ([MarshalAs (UNMANAGEDTYPE.LPWSTR)] string Servername,[marshalas ( UNMANAGEDTYPE.LPWSTR)] string username,int level,ref user_info_1 buf, int error);

/**/////Code End

Using these declarations, we can easily get and modify user settings. In the following code, we will get the user information of the user Usertestone we added earlier, and we will modify some user information.

/**//////Code Snippet 1.7 NetUserGetInfo

INTPTR BufPtr;
User_info_1 User = new User_info_1 ();
if (NetUserGetInfo (null, "Administrator", 1,out bufptr)!=0)
{
MessageBox.Show ("Error getting User Info", "error", Messageboxbuttons.ok,messageboxicon.error);
}
User = (user_info_1) marshal.ptrtostructure (BufPtr, typeof (User_info_1));
MessageBox.Show ("Users Name:" + user.usri1_name + "users Comments:" + user.comment + "Users privilege level:" + User. USRI1_PRIV);

/**/////Code End

In this case, we use marshaling to get the data, which is the only effective way I can find it.

/**//////Code Snippet 1.8 Netusetsetinfo

User_info_1 Update = new User_info_1 ();
Update.comment = "This are our C # Updated comment";
Update.usri1_priv = 2; This can is obtained programmatically using NetUserGetInfo
if (NetUserSetInfo (null, "Usertestone", 1,ref update,0)!=0)
{
MessageBox.Show ("Error Setting User Info", "error", Messageboxbuttons.ok,messageboxicon.error);
}

/**/////Code End
Let's conclude that NetUserSetInfo relies on netusergetinfo to work properly. As with other network functions, if you modify the first parameter to the computer name, you will be able to use the function remotely.

Modifying user passwords using C #

Another important function of network management is to modify the password. The function NetUserChangePassword is based on our ability to provide the current user's original password. The declaration NetUserChangePassword can use the following code fragment:
/**//////Code Snippet 1.9 statement

[DllImport ("Netapi32.dll")]
extern static int NetUserChangePassword ([MarshalAs (UNMANAGEDTYPE.LPWSTR)] string Domainname,[marshalas ( UNMANAGEDTYPE.LPWSTR)] string Username,[marshalas (UNMANAGEDTYPE.LPWSTR)] string Oldpassword,[marshalas ( UNMANAGEDTYPE.LPWSTR)] string newpassword);

/**/////Code End

Using the above statement, if we know the user's original password, we can modify the user's password. Again, we can use the function remotely by simply changing the null parameter to the name of a particular computer.

/**//////Code Snippet 2.0 NetUserChangePassword

if (NetUserChangePassword (null, "Usertestone", "Password", "Ournewpassword")!=0)
{
MessageBox.Show ("Error changing User Password", "error", Messageboxbuttons.ok,messageboxicon.error);
}

/**/////Code End

get a list of users

When managing a network, it is important to have an accurate list of network users or computers. To get such a list, we must use the Netuserenum function, which returns the user's name and related data to a struct. In this example, we intend to use the USER_INFO_0 structure to pass the value. Since we only needed to get the username, I added the username element to the declaration of the struct body. Note that this function uses a network buffer (network buffer), which must be freed to conserve resources, and we can use the NetApiBufferFree function. Once we have made the declaration, we can use the following code fragment to get the user list.

/**//////Code Snippet 2.1 statement

[StructLayout (LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct USER_INFO_0
{
Public String Username;
}

[DllImport ("Netapi32.dll")]
extern static int Netuserenum ([MarshalAs (UNMANAGEDTYPE.LPWSTR)] string servername, int level, int filter, out IntPtr bufpt R, int prefmaxlen, out int entriesread, out int totalentries, out int resume_handle);

[DllImport ("Netapi32.dll")]
extern static int NetApiBufferFree (INTPTR Buffer);

/**/////Code End

Once we have made the declaration, we can use the following code fragment to get the user list.

/**//////Code Snippet 2.2 Netuserenum

int entriesread;
int totalentries;
int Resume;
INTPTR BufPtr;

Netuserenum (NULL, 0, 2, out BufPtr,-1, out Entriesread, out totalentries, out Resume);

if (entriesread> 0)
{
user_info_0[] Users = new User_info_0[entriesread];
IntPtr iter = bufptr;
for (int i=0 i < entriesread; i++)
{
Users[i] = (user_info_0) marshal.ptrtostructure (ITER, typeof (User_info_0));
iter = (INTPTR) (int) iter + marshal.sizeof (typeof (User_info_0));
MessageBox.Show (Users[i]. Username);
}
Networkapi.netapibufferfree (BUFPTR);
}
/**/////Code End
The above code enumerates the users on the local computer by MessageBox. We can also specify a remote computer by replacing the null string parameter.

identify the relationships of user groups

The last function we want to understand in this article is netusergetlocalgroups. This function allows us to determine which groups a user belongs to and display those groups. As with the previous function, we need to clear the network buffer after using the function. The NetUserGetLocalGroups declaration also requires a struct LOCALGROUP_USERS_INFO_0 to return the group name.

/**//////Code Snippet 2.3 statement
[StructLayout (LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct LOCALGROUP_USERS_INFO_0
{
public string groupname;
}

[DllImport ("Netapi32.dll")]
public extern static int netusergetlocalgroups ([MarshalAs (UNMANAGEDTYPE.LPWSTR)] string Servername,[marshalas ( UNMANAGEDTYPE.LPWSTR)] string username, int level, int flags, out IntPtr bufptr, int prefmaxlen, out int entriesread, out int totalentries);
/**/////Code End
With the above declaration, we can call the function in code similar to the previous function.

/**//////Code Snippet 2.4 netusergetlocalgroups
int entriesread;
int totalentries;
INTPTR BufPtr;

NetUserGetLocalGroups (NULL, "Administrator", 0,0,out bufptr,1024,out Entriesread, out totalentries);

if (entriesread> 0)
{
localgroup_users_info_0[] retgroups = new Localgroup_users_info_0[entriesread];
IntPtr iter = bufptr;
for (int i=0 i < entriesread; i++)
{
Retgroups[i] = (localgroup_users_info_0) marshal.ptrtostructure (ITER, typeof (Localgroup_users_info_0));
iter = (INTPTR) (int) iter + marshal.sizeof (typeof (Localgroup_users_info_0));
MessageBox.Show (Retgroups[i].groupname);
}
NetApiBufferFree (BUFPTR);
}
/**/////Code End

The example above returns the group where the user administrator is located. Through this article, we have learned how to pass. NET platform invoke method uses the network functions associated with managing users. About the original author [see original]


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.