Search
Module:
Directory

   Desktop Functions:

   Smart Device Functions:


Show Recent Changes
Subscribe (RSS)
Misc. Pages
Comments
FAQ
Helpful Tools
Playground
Suggested Reading
Website TODO List
Download Visual Studio Add-In

Search Results for "Hi" in [All]

psapi

.
Summary
EmptyWorkingSet wherever possible moves an applications pages from RAM to the page file, therefore freeing physical RAM. Good for giving you a bit more memory for the programs you need when Windows doesn't free up memory from something that has been sitting idle for hours.
.

            throw; //throw the error in this case.

.

The signature above only works on 32-bit machines. Here's a stab at something that works on x86 as well as x864.

.

Remember, this ONLY enumerates device drivers that are currently loaded. If a plug-n-play device is not inserted, its driver probably won't be enumerated by EnumDeviceDrivers. With the 'load addresses' returned by this function, you can get the drivers' base names using the GetDeviceDriverBaseName function.

.

        GCHandle gch = GCHandle.Alloc(hMods, GCHandleType.Pinned); // Don't forget to free this later

.

This function takes a 'load address' that needs to be obtained from EnumDeviceDrivers.

.

I had trouble using the original C# signature above, but found that this one works:

.

Using this method in conjuction with EnumProcessModules:

.

        GCHandle gch = GCHandle.Alloc(hMods, GCHandleType.Pinned); // Don't forget to free this later

.

        /// <summary>The size of this structure, in bytes.</summary>

.

        /// pages (using VirtualAlloc with MEM_COMMIT) changes this value immediately; however,

.

        /// without extending the paging file(s). This number can change if memory is added

.

        /// file can be extended, this is a soft limit.</summary>

.

        /// <summary>The amount of physical memory currently available, in pages. This is the

.

        /// <summary>The amount of system cache memory, in pages. This is the size of the

.

    // While Minimizing Impact To Existing Code

.

This can be used in place of the GetModuleFileName call, which doesn't work on processes that haven't been loaded by the current one.

.

I found this to be more comprehensive than GetModuleFileNameEx. Didnt need to enumerate windows or modules

.

/** This gets the filename of the process image. Path is in device format **/

.

      public uint PagefileUsage;          // The Commit Charge value in bytes for this process (SIZE_T). Commit Charge is the total amount of memory that the memory manager has committed for a running process.

.

      public uint PeakPagefileUsage;      // The peak value in bytes of the Commit Charge during the lifetime of this process (SIZE_T).

.

Presently a rioting noise was heard without. Starting up, the landlord cried, "That's the Grampus's crew. I seed her reported in the offing this morning; a three years' voyage, and a full ship. Hurrah, boys; now we'll have the latest news from the Feegees."

netapi32

.

Ä Æ'” ‰FE²ßŒ&/)aÿϐbýmWÂo0óö»öːßÑïIÎTUƒ"éÿóÑ­ÿ÷0µ kZ™sUœºÀ*Gëÿ‘ò”‡™<kù¯éBqہ¸ æ\OϭƑµÜÓ{—fŒï2··ú€ÁÔ¦§B¸áè› ØiËE¢ „Í! Ø`?nêö;¯=oNß³ãºp W ÞûĆÊ'ðÅchhêkÙ Œ=֝åiwS-™®’h3ÃCVό?1Mò6_†‹YmT%É­¶6©2šÐà¿f›,#DhV=Àt·£J!Ø÷mö+T "±œï´b—Ϊ h®!¤¨Ž€ÆMٍýñ2SΞ%êš½‰;R”òíK4¤Ø«'x3­¾¡; Ƥá”&Ò¸žZ<;8à|ªíßÙµCí%®€š7n¥ugfn´vþ¯—, cqs^Å1öÂ̳u‰ùˆGà- wS0 aX5ã”!䛂-=ŒJ¤*ä±§5ë"æ:Î kž“»³;ÜÅ8'g-TÎÑ!6yÝÖÀ•Í€ŠB.ƒ¼l<ËhIžÑ†J<ÅJ#ø…ÈW ÜÌoË(ãFmËï,âÁô¤»½‰¾³µÛVKÿx‚Jí¾6iø`.┭ RŒ±©øÔðÌÌkõ£Â0†£ÑN ™ÒviJdû1OQzª•3aÎ?Š;sÊ6 ü©G” áŸ5ûÐÊ:}=ڑ62}á¸SÍ|½5yž‰„ØXYÑ;ìÌÞ»™Ý$û >¶cÝ'¡ °

.
  • computerName: String that specifies the name of the remote server to process this function. This parameter must be the name of a domain controller. A non-domain controller can call this function by calling DsGetDcName to find the domain controller.
.
  • socketAddresses: An array of SOCKET_ADDRESS structures that contain the addresses to convert. Each address in this array must be of the type AF_INET. EntryCount contains the number of elements in this array.
.
  • siteNames: An array of null-terminated string pointers that contain the site names for the addresses. Each element in this array corresponds to the same element in the socketAddresses array. An element is NULL if the corresponding address does not map to any known site or if the address entry is not of the proper form. The caller must free this array when it is no longer required by calling NetApiBufferFree.
.

Prior to calling he DsAddressToSiteNames function, a SOCKET_ADDRESS structure must be created for each address that is to be resolved to a site name. This can be done using the WSAStringToAddress method shown in the sample code.

.

        // Get the site name for this address

.

        // If a site could not be found for this address, pSiteName will be 0, so only marshal out the string if

.

Domains is an out parameter that receives a pointer to an array of DS_DOMAIN_TRUSTS structures. Each structure in this array contains trust data about a domain. The caller must free this memory when it is no longer required by calling NetApiBufferFree.

.

     // Make the call - not doing anything special with the result value here

.
Summary
The DsGetDcName function returns the name of a domain controller in a specified domain. This function accepts additional domain controller selection criteria to indicate preference for a domain controller with particular characteristics.
.

Pointer to a PDOMAIN_CONTROLLER_INFO value that receives a pointer to a DOMAIN_CONTROLLER_INFO structure that contains data about the domain controller selected. This structure is allocated by DsGetDcName. The caller must free the structure using the NetApiBufferFree function when it is no longer required.

.

     IntPtr SockAddresses, //must free this if using (SocketAddressCount > 1)

.

     out IntPtr DnsHostName //will have to marshal this one manually

.

[out, optional] Pointer to a ULONG value that receives the number of elements in the SockAddresses array. If this parameter is NULL, socket addresses are not retrieved.

.

[out, optional] Pointer to an array of SOCKET_ADDRESS structures that receives the socket address data for the domain controller. SockAddressCount receives the number of elements in this array.

.

The caller must free this memory when it is no longer required by calling LocalFree.

.

This parameter is ignored if SockAddressCount is NULL.

.

[out, optional] Pointer to a string pointer that receives the DNS name of the domain controller. This parameter receives NULL if no host name is known. The caller must free this memory when it is no longer required by calling NetApiBufferFree.

.

while (!endLoop)

.

         case ERROR_FILEMARK_DETECTED: //127 - I think...

.

        while (!endLoop)

.

out Pointer to a HANDLE value that receives the domain controller enumeration context handle. This handle is used with the DsGetDcNext function to identify the domain controller enumeration operation. This handle is passed to DsGetDcClose to close the domain controller enumeration operation.

.

    // this is a great call, it will give you all the DC's that COVER a site, not just the DC's in that site:

.

    /// <summary>Retrieves state data for the computer, which includes the state of the directory service installation and domain data.</summary>

.

    /// <param name="server">Name of the computer on which to retrieve state data.</param>

.

    /// <summary>The directory service is running on this computer.</summary>

.

    /// <summary>The directory service is running as read-only on this computer.</summary>

.

    public enum MachineRole

.

    private MachineRole machineRole;

.

    public MachineRole MachineRole

.

        get { return this.machineRole; }

.

        get { return this.flags; }

.

        get { return this.domainNameFlat; }

.

        get { return this.domainNameDns; }

.

        get { return this.domainForestName; }

.

        get { return this.domainGloballyUniqueIdentifier; }

.

    /// <summary>The third data.</summary>

.

    private short thirdData;

.

        get { return this.firstData; }

.

        get { return this.secondData; }

.

    /// <summary>Gets the third data.</summary>

.

    /// <value>The third data.</value>

.

    public short ThirdData

.

        get { return this.thirdData; }

.

        get { return this.fourthData; }

.

        get { return this.operationStateAttributes; }

.

        get { return this.operationStateAttributes; }

.

        get { return this.serverState; }

.

    /// <param name="server">Name of the computer on which to retrieve the information.</param>

.

    /// <param name="server">Name of the computer on which to retrieve the information.</param>

.

    /// <param name="server">Name of the computer on which to retrieve the information.</param>

.

    /// <summary>Gets state data for the computer, which includes the state of the directory service installation and domain data.</summary>

.

    /// <param name="server">Name of the computer on which to retrieve state data.</param>

.

I could not help it, but I began to feel suspicious of this "dark complexioned" harpooneer. At any rate, I made up my mind that if it so turned out that we should sleep together, he must undress and get into bed before I did.

.

With all the different information you can get with just one command; this one sure is difficult. Very, very little documentation on this because Microsoft probably doesn't want easy access to these. My company has allowed me to contribute my findings as long as I mention it. We are Digital Boundary Group, based in London, Ontario, Canada, and we do penetration testing. Please visit us at http://digitalboundary.net I will be allowed to continue my contributions as long as my company does not lose credit for its contributions.

.

        //Everything from here until the "Good Stuff", was copied from this site

.

        if (!LookupAccountName(this.ResourceName, this.UserName, Sid, ref cbSid, referencedDomainName, ref cchReferencedDomainName, out sidUse))

.

            if (!LookupAccountName(this.ResourceName, this.UserName, Sid, ref cbSid, referencedDomainName, ref cchReferencedDomainName, out sidUse))

.

        aSystemName.SetTo(this.ResourceName);

.

        //This example gets Audit Policy information

.

        //do what you want with the retval, this is a pretty lazy example

.

        //Microsoft states that this could be an arbitrary number of elements because they may expand upon this in later Windows versions

.

        //pevents.MaximumAuditEventCount gives you the number of elements, take this number of elements and Marshall copy the array

.

Changed VB.NET Signature from "ByRef buffer" to "ByVal buffer". With ByRef you get a significant memory leak, with ByVal everything is fine.

.

There is no indication that the NetApiBufferFree function sets the last error code, so SetLastError attribute should not be set (this removes extra calls in the interop layer to store the last error code). Also, the CharSet property on the attribute need not be applied either, as there is only one version of this function.

.

I had a mapping error using the flag as a long. A DWORD is a unsigned 32 bit int. I modified this to match.

.

Also on MSDN, there is a more detailed example of using this API:

.

    /// <param name="Level">[in] Specifies the information level of the request. This parameter can be one of the following values. </param>

.

    /// <param name="PrefMaxLen">[in] Specifies the preferred maximum number of bytes that should be returned by this enumeration function call in the information structure buffer. If this parameter is MAX_PREFERRED_LENGTH, the function allocates the amount of memory required for the data. For more information, see the following Remarks section. This parameter is ignored if you specify level 200 or level 300.</param>

.

    /// <param name="Buffer">[out] Pointer to the address of a buffer that receives the requested information structures. The format of this data depends on the value of the Level parameter. This buffer is allocated by the system and must be freed using the NetApiBufferFree function. </param>

.

    /// <param name="ResumeHandle">[in, out] Pointer to a value that contains a handle which is used to continue the enumeration. The handle should be zero on the first call and left unchanged for subsequent calls. For more information, see the following Remarks section. Windows Server 2003:  If ResumeHandle is NULL, then no resume handle is stored.</param>

.

        Public shi0_netname As String

.

    string shi0_netname;

.

[2009-04-02] C# User Defined types added by dalehirt

.

    [MarshalAs(UnmanagedType.LPWStr)] string ServerName,        // This parameter is currently ignored and should be NULL

.

    [MarshalAs(UnmanagedType.LPWStr)] string ShareName,        // This parameter is currently ignored and should be NULL.

.

    [MarshalAs(UnmanagedType.LPWStr)] string ServerName,    // This parameter is currently ignored and should be NULL

.

    [MarshalAs(UnmanagedType.LPWStr)] string ShareName,    // This parameter is currently ignored and should be NULL.

.

    /// <param name="ShareName">[in] Pointer to a string that specifies the name of the shared folder or the path to a folder within a shared folder on the host server that the Dfs link references. </param>

.

    ''' <param name="ServerName">[in] Pointer to a string that specifies the name of the host server that the Dfs link references. Set this parameter to NULL if the link and all link targets are to be removed.</param>

.

    ''' <param name="ShareName">[in] Pointer to a string that specifies the name of the shared folder or the path to a folder within a shared folder on the host server that the Dfs link references. Set this parameter to NULL if the link and all link targets are to be removed.</param>

.

    /// <param name="ShareName">[in, optional] Pointer to a string that specifies the name of the shared folder or the path to a folder within a shared folder on the host server that the Dfs link references. </param>

.

    /// <param name="Level">[in] Specifies the information level of the data. This parameter can be one of the following values. </param>

.

    /// <param name="Buffer">[in] Pointer to a buffer that specifies the data. The format of this data depends on the value of the Level parameter.</param>

.

    if (MessageBox.Show(this, "Are you sure you want to close this connection?" == DialogResult.Yes))

.

    If MsgBox("Are you sure you want to disconnect this resource?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then

.

    dwStatus = NetFileEnum(TextBox1.Text, Nothing, Nothing, 3, pBuffer, MAX_PREFERRED_LENGTH, dwReadEntries, dwTotalEntries, IntPtr.Zero)

.
Summary
The NetGetDCName function returns the name of the primary domain controller (PDC). It does not return the name of the backup domain controller (BDC) for the specified domain. Also, you cannot remote this function to a non-PDC server.
.

      Dim result As NetApiStatus = NetGetDCName(Nothing, Nothing, domainInfo)

.

However, this throws an exception (undocumented) on some PC's ("Logon failure") which pretty much renders it useless. Bummer.

.

        Dim groupInfo As NetGroupInformation = Nothing

.

          NETSETUP_MACHINE_PWD_PASSED = 0x00000080,

.

To join a machine to a domain the same way that netdom.exe does, use the flags NETSETUP_JOIN_DOMAIN and NETSETUP_ACCT_CREATE. (I determined this by using a debugger to watch which flags netdom used.)

.
NOTE
If the machine is already in a domain use (JoinOptions.NETSETUP_JOIN_DOMAIN + JoinOptions.NETSETUP_DOMAIN_JOIN_IF_JOINED). JoinOptions.NETSETUP_DOMAIN_JOIN_IF_JOINED used on it's own always returns NERR_SetupAlreadyJoined.
.

        NETSETUP_MACHINE_PWD_PASSED = 0x00000080,

.

This page is a modified copy/paste from the NetLocalGroupEnum.

.

The largest challenge is marshaling the pointer to the array of structures which the output is placed in.

.

In this example, I use a do/while which doubles the size of the buffer until it is large enough to contain all of the groups that are on the server. The API call is designed so that you can read sequentially (ERROR_MORE_DATA), but I didn't want to deal with marshaling returned data stored in more than one of the pointers to the array of structures which the output is placed in!

.

            while(err==234);    // and start over

.

Here's some sample code that can do this using System.DirectoryServices

.

        DirectoryEntry user = domainDE.Children.Find(userName, "user");

.

        DirectoryEntry group = localDE.Children.Find(groupName, "group");

.

The largest challenge is marshaling the pointer to the array of structures which the output is placed in.

.

In this example, I use a do/while which doubles the size of the buffer until it is large enough to contain all of the groups that are on the server. The API call is designed so that you can read sequentially (ERROR_MORE_DATA), but I didn't want to deal with marshaling returned data stored in more than one of the pointers to the array of structures which the output is placed in!

.

            while(err==234);    // and start over

.

Code to read the membership of Local Groups (ideally used with NetLocalGroupEnum )

.

        /// the security database, which is the security accounts manager (SAM) database or, in the case

.

    {        //I used this to retrieve the type of group so I could use an icon in a treeview if desired.

.
Summary
This function sends a buffer of information to a registered message alias.
.

    ''' <param name="servername">Pointer to a constant string that specifies the DNS or NetBIOS name of the remote server on which the function is to execute.

.

    ''' If this parameter is NULL, the local computer is used.</param>

.

    ''' <param name="msgname">Pointer to a constant string that specifies the message alias to which the message buffer should be sent.</param>

.

    ''' If this parameter is NULL, the message is sent from the local computer name.</param>

.

    ''' ERROR_NOT_SUPPORTED This network request is not supported.

.

    ''' <remarks>If you call this function on a domain controller that is running Active Directory, access is allowed or denied based on

.

    ''' the access control list (ACL) for the securable object. The default ACL permits only Domain Admins and Account Operators to call this function.

.

    ''' On a member server or workstation, only Administrators and Server Operators can call this function.

.

    ''' Windows NT:  No special group membership is required to execute the NetMessageBufferSend function on a LAN Manager or a Windows NT system.

.

    ''' Admin, Accounts, Print, or Server Operator group membership is required to successfully execute NetMessageBufferSend on a remote server.

.

This is a simple console program which lets you send messages (quite similar to the NET SEND command...).

.

For example you can use the name of your machine as srcName a'nd dstName and the message will be sent to yourself

.
Summary
The NetQueryDisplayInformation function returns user account, computer, or group account information. Call this function to quickly enumerate account information for display in user interfaces.
.

I hugely increased the speed of this API by doing the following:

.

        while ((lret == ERROR_MORE_DATA))

.

    public struct NET_DISPLAY_MACHINE

.

    while ((lret == ERROR_MORE_DATA))

.

    while ((lret == ERROR_MORE_DATA))

.

    NET_DISPLAY_MACHINE mac = new NET_DISPLAY_MACHINE ();

.

    while ((lret == ERROR_MORE_DATA))

.

                mac = (NET_DISPLAY_MACHINE) Marshal.PtrToStructure(x,typeof(NET_DISPLAY_MACHINE));

.
Summary
Renames an already joined machine on a domain.
.

    internal static extern int NetRenameMachineInDomain(

.

        string lpNewMachineName,

.

     Declare Function NetRenameMachineInDomain Lib "netapi32.dll" (TODO) As TODO

.

lpServer - (in) Pointer to a constant string that specifies the DNS or NetBIOS name of the computer on which to call the function. If this parameter is NULL, the local computer is used. Windows NT: This string must begin with \\.

.

lpNewMachineName - (in) Pointer to a constant string that specifies the new name of the computer. If specified, the local computer name is changed as well. If this parameter is NULL, the function assumes you have already called the SetComputerNameEx function.

.

lpAccount - (in) Pointer to a constant string that specifies an account name to use when connecting to the domain controller. If this parameter is NULL, the caller's context is used.

.

lpPassword - (in) If the lpAccount parameter specifies an account name, this parameter must point to the password to use when connecting to the domain controller. Otherwise, this parameter must be NULL.

.

fRenameOptions - (in) Specifies the rename options. If this parameter is NETSETUP_ACCT_CREATE, the function renames the account in the domain.

.

    internal static extern int NetRenameMachineInDomain(

.

        string lpNewMachineName,

.

    private void RenameMachine()

.

        //This function will change the current PC's name to "PCNEWNAME" using the given domain account.  This changes it both locally and on the domain.

.

        error = NetRenameMachineInDomain(null, "PCNEWNAME", _domainUser, _domainPassword, NETSETUP_ACCT_CREATE);

.
Documentation
[NetRenameMachineInDomain] on MSDN
.

    /// The name of the machine to add the scheduled task to.

.

    ''' The name of the machine to add the scheduled task to.

.

    /// Bitmask is from the first to thirty first, lowest to highest bit, or 0 if the job will be run only once.

.

    /// Bitmask is from Monday to Sunday, from lowest to highest bit, or 0 if the job will be run only once.

.

This will add a scheduled task using the older api that AT.EXE uses. Because of this, you will not be able to name the scheduled task.

.

                        //Cast the pointer to a ulong so this addition will work on 32-bit or 64-bit systems.

.

                        // add the machine name and comment to the arrayList.

.

            while

.

The System.Data.Sql.SqlDataSourceEnumerator class is an alternative to this API, for enumerating SQL Servers on a network.

.

    public bool Hidden;

.

    Dim sv102_hidden As Boolean

.

2. Pass in vbNullString as the first parameter if you are querying the local machine. Otherwise, just pass in the name of the machine.

.
Summary
Deletes a network session. A better explanation would be that this api disconnects another computer which is connected to your computer. If the user is copying files then he/she will receive an error. This however does not stop the user from reconnecting.
.

    ''' <param name="serverName">[in] Pointer to a string that specifies the DNS or NetBIOS name of the remote server on which the function is to execute. If this parameter is NULL, the local computer is used. </param>

.

    ''' <param name="username">[in] Pointer to a string that specifies the name of the user whose session is to be terminated. If this parameter is NULL, all users' sessions from the client specified by the UncClientName parameter are to be terminated.</param>

.

NetSessionDel(Nothing, Nothing, "USERNAMETODELETE")

.

    ''' <param name="serverName">[in] Pointer to a string that specifies the DNS or NetBIOS name of the remote server on which the function is to execute. If this parameter is NULL, the local computer is used.</param>

.

    ''' <param name="UncClientName">[in] Pointer to a string that specifies the name of the computer session for which information is to be returned. If this parameter is NULL, NetSessionEnum returns information for all computer sessions on the server.</param>

.

    ''' <param name="userName">[in] Pointer to a string that specifies the name of the user for which information is to be returned. If this parameter is NULL, NetSessionEnum returns information for all users.</param>

.

    ''' <param name="level">[in] Specifies the information level of the data. This parameter can be one of the following values.

.

    ''' [out] Pointer to the buffer that receives the data. The format of this data depends on the value of the level parameter.

.

    ''' This buffer is allocated by the system and must be freed using the NetApiBufferFree function. Note that you must free the buffer even if the function fails with ERROR_MORE_DATA.

.

    ''' <param name="prefmaxlen">[in] Specifies the preferred maximum length of returned data, in bytes. If you specify MAX_PREFERRED_LENGTH, the function allocates the amount of memory required for the data. If you specify another value in this parameter, it can restrict the number of bytes that the function returns. If the buffer size is insufficient to hold all entries, the function returns ERROR_MORE_DATA.</param>

.

    ''' <param name="totalentries">[out] Pointer to a value that receives the total number of entries that could have been enumerated from the current resume position. Note that applications should consider this value only as a hint.</param>

.

    ''' <param name="resume_handle">[in, out] Pointer to a value that contains a resume handle which is used to continue an existing session search. The handle should be zero on the first call and left unchanged for subsequent calls. If resume_handle is NULL, no resume handle is stored.</param>

.

        /// LEVEL specified is not valid for this call.

.

        /// Security context does not have permission to make this call.

.

            while (res==(int)NERR.ERROR_MORE_DATA);

.

            [MarshalAs(UnmanagedType.LPWStr)] public string shi502_netname;

.

            public SHARE_TYPE shi502_type;

.

            [MarshalAs(UnmanagedType.LPWStr)] public string shi502_remark;

.

            public Int32 shi502_permissions;

.

            public Int32 shi502_max_uses;

.

            public Int32 shi502_current_uses;

.

            [MarshalAs(UnmanagedType.LPWStr)] public string shi502_path;

.

            [MarshalAs(UnmanagedType.LPWStr)] public string shi502_passwd;

.

            public Int32 shi502_reserved;

.

            public IntPtr shi502_security_descriptor;

.

        ' Add this value to one of the above values

.

        Public shi2_netname As String

.

        Public shi2_type As ShareType

.

        Public shi2_remark As String

.

        Public shi2_permissions As SharePermissions

.

        Public shi2_max_uses As Integer

.

        Public shi2_current_uses As Integer

.

        Public shi2_path As String

.

        Public shi2_passwd As String

.

        shi2_netname = netName

.

        shi2_type = type

.

        shi2_remark = remark

.

        shi2_permissions = permissions

.

        shi2_max_uses = maxUses

.

        shi2_current_uses = 0

.

        shi2_path = path

.

        shi2_passwd = passwd

.

This function will take as it's third parameter, a number of structures. The second parameter defines which level the third parameter structure is. Acceptable structures are SHARE_INFO_2, SHARE_INFO_502, and under Windows 9x/ME, SHARE_INFO_50.

.

    string shareDesc = "This is a test share kekelar2000";

.

    info.shi502_netname = shareName;

.

    info.shi502_type = SHARE_TYPE.STYPE_DISKTREE;

.

    info.shi502_remark = shareDesc;

.

    info.shi502_permissions = 0;    // ignored for user-level security

.

    info.shi502_max_uses = -1;

.

    info.shi502_current_uses = 0;    // ignored for set

.

    info.shi502_path = path;

.

    info.shi502_passwd = null;        // ignored for user-level security

.

    info.shi502_reserved = 0;

.

    info.shi502_security_descriptor = IntPtr.Zero;

.

Dim shi2 As SHARE_INFO_2

.

shi2.shi2_netname = sharename"      ' share name

.

shi2.shi2_type = ShareType.Disk     ' disk drive

.

shi2.shi2_remark = ""           ' share comment

.

shi2.shi2_permissions = SharePermissions.ACCESS_NONE

.

shi2.shi2_max_uses = -1        ' unlimited    

.

shi2.shi2_current_uses = 0

.

shi2.shi2_path = "c:\myshare"

.

shi2.shi2_passwd = Nothing      ' no password

.

retval = NetShareAdd(ServerName, 2, shi2, Nothing)

.
  • servername: String that specifies the DNS or NetBIOS name of the remote server on which the function is to execute. If this parameter is NULL, the local computer is used.
.
  • type: Specify the type of the shared device. This parameter is set only if the function returns successfully.
.
Summary
Deletes a network share on either a local or remote machine
.

//this one's easy too

.

' This one is easy!

.
Summary
Retrieves and enumerates over all shares on a specified machine. Can specify the amount of information gathered with the "level" parameter. The less info you get over a WAN the better because a server with 1000+ shares' information pulled over the network can be quite inefficient if you're getting a bunch of data you don't need.
.

     public string shi0_netname;

.

I believe that all of these samples are slightly incorrect in that they do not deal with the case where NetShareEnum does not retrieve all of the shares on a server in a single call. The caller is supposed to check for ERROR_MORE_DATA and then do the appropriate thing. This may be an edge case not worrying about, but anyone writing code for big environments should validate the assumption that all shares will be fetched with a single call.

.

            While i < entriesRead

.

            End While

.

Dim shi2 As SHARE_INFO_2

.

     shi2 = Marshal.PtrToStructure(currentPtr, GetType(SHARE_INFO_2))

.

     If System.String.Compare(shi2.shi2_path, "c:\deletemeplease" True) = 0 Then

.

       DelRetVal = NetShareDel(ServerName, shi2.shi2_netname, 0)

.

         SHARE_INFO_0 shi0 = (SHARE_INFO_0)Marshal.PtrToStructure(currentPtr,typeof(SHARE_INFO_0));

.

         listBox1.Items.Add(shi0.shi0_netname);

.

        public string shi1_netname;

.

        public uint shi1_type;

.

        public string shi1_remark;

.

        this.shi1_netname = sharename;

.

        this.shi1_type = sharetype;

.

        this.shi1_remark = remark;

.

        return shi1_netname;

.

            SHARE_INFO_1 shi1 = (SHARE_INFO_1)Marshal.PtrToStructure(currentPtr, typeof(SHARE_INFO_1));

.

            ShareInfos.Add(shi1);

.

' What is mission. This one works well. Share type 0 is a normal shared folder. I don't know the other types

.

        Shares = Nothing

.

        If Shares Is Nothing Then

.

    Const ERROR_ACCESS_DENIED As Long = 5&      ' The user has insufficient privilege for this operation.

.

    Const NERR_RemoteOnly As Long = 2106&       ' This operation can be performed only on a server.

.

    Const NERR_RemoteErr As Long = 2127&        ' Error encountered while remotely.  executing function

.

    Const NERR_BadTransactConfig As Long = 2141&    ' The server is not configured for this transaction;  IPC$ is not shared.

.

    <MarshalAs(UnmanagedType.LPWStr)> Dim shi2_netname As String

.

    Dim shi2_type As Integer

.

    <MarshalAs(UnmanagedType.LPWStr)> Dim shi2_remark As String

.

    Dim shi2_permissions As Integer

.

    Dim shi2_max_uses As Integer

.

    Dim shi2_current_uses As Integer

.

    <MarshalAs(UnmanagedType.LPWStr)> Dim shi2_path As String

.

    <MarshalAs(UnmanagedType.LPWStr)> Dim shi2_passwd As String

.

        While i < entriesRead

.

            Shares.Add(si.shi2_netname, si.shi2_path, si.shi2_type, si.shi2_remark)

.

        End While

.
Summary
Gets information about a single share. BufPtr points to a SHARE_INFO_2 structure. See NetShareEnum for example code of how to convert this to a usable structure.
.

    Const ERROR_ACCESS_DENIED As Long = 5&          ' The user has insufficient privilege for this operation.

.

    Const NERR_RemoteOnly As Long = 2106&           ' This operation can be performed only on a server.

.

    Const NERR_RemoteErr As Long = 2127&            ' Error encountered while remotely.  executing function

.

    Const NERR_BadTransactConfig As Long = 2141&        ' The server is not configured for this transaction;  IPC$ is not shared.

.

        <MarshalAs(UnmanagedType.LPWStr)> Dim shi2_netname As String

.

        Dim shi2_type As Integer

.

        <MarshalAs(UnmanagedType.LPWStr)> Dim shi2_remark As String

.

        Dim shi2_permissions As Integer

.

        Dim shi2_max_uses As Integer

.

        Dim shi2_current_uses As Integer

.

        <MarshalAs(UnmanagedType.LPWStr)> Dim shi2_path As String

.

        <MarshalAs(UnmanagedType.LPWStr)> Dim shi2_passwd As String

.

            ' Note: By Sending Null were looking at current machine

.

            sReturnBasePath = pCurrent.shi2_path

.

                Throw New Exception("NetShareGetInfo: ERROR_ACCESS_DENIED -> The user has insufficient privilege for this operation.")

.

                Throw New Exception("NetShareGetInfo: NERR_RemoteOnly -> This operation can be performed only on a server.")

.

                Throw New Exception("NetShareGetInfo: NERR_RemoteErr -> Error encountered while remotely executing function")

.

                Throw New Exception("NetShareGetInfo: NERR_BadTransactConfig -> The server is not configured for this transaction;  IPC$ is not shared.")

.

            public string shi502_netname;

.

            public uint shi502_type;

.

            public string shi502_remark;

.

            public Int32 shi502_permissions;

.

            public Int32 shi502_max_uses;

.

            public Int32 shi502_current_uses;

.

            public string shi502_path;

.

            public IntPtr shi502_passwd;

.

            public Int32 shi502_reserved;

.

            public IntPtr shi502_security_descriptor;

.

     Result  = 5&             ' The user has insufficient privilege for this operation.

.

     Result  = 2106&                 '   This operation can be performed only on a server.

.

     Result = 2127&                '   Error encountered while remotely.  executing function

.

     Result = 2141&              '   The server is not configured for this transaction;  IPC$ is not shared.

.

            public string shi2_netname;

.

            public uint shi2_type;

.

            public string shi2_remark;

.

            public uint shi2_permissions;

.

            public uint shi2_max_uses;

.

            public uint shi2_current_uses;

.

            public string shi2_path;

.

            public string shi2_passwd;

.

                path = shareInfo.shi2_path;

.

        const int NERR_NetNameNotFound = 2310; // This shared resource does not exist.

.

        Console.WriteLine("Hit <ENTER> to close window...")

.
Summary
The equivalent counter-part to NetShareGetInfo. This lets you set information about an existing share.
.

lpServer - (in) Pointer to a constant string that specifies the DNS or NetBIOS name of the computer on which the function is to execute. If this parameter is NULL, the local computer is used.

.

lpAccount - (in) Pointer to a constant string that specifies the account name to use when connecting to the domain controller. The string must specify either a domain NetBIOS name and user account (for example, "REDMOND\user") or the user principal name (UPN) of the user in the form of an Internet-style login name (for example, "someone@example.com"). If this parameter is NULL, the caller's context is used.

.

lpPassword - (in) If the lpAccount parameter specifies an account name, this parameter must point to the password to use when connecting to the domain controller. Otherwise, this parameter must be NULL.

.

fUnjoinOptions - (in) Specifies the unjoin options. If this parameter is NETSETUP_ACCT_DELETE, the account is disabled when the unjoin occurs. Note that this option does not delete the account. Currently, there are no other unjoin options defined.

.

useInfo.ui2_remote    = @"\\machine\share";

.

// This code steps through the returned buffer of NetUseEnum and Marshals the buffer member to the structure

.

            while(li<lRead)

.

        NetUseEnum(Nothing, 2, lBuffer, UInt32.MaxValue, lRead, lTotal, lHandle)

.
Summary
Provide a user account and its existing password, and this API allows you to choose a new password for the account.
.

    const int NERR_InvalidComputer = (NERR_BASE+251); /* This computer name is invalid. */

.

    // Passing this for 'filter'

.

    //Do not use this code it is severely broken

.

    //Do not use this code it is severely broken

.

        DirectoryEntry directoryEntry = new DirectoryEntry("WinNT://" + Environment.MachineName);

.

        foreach (DirectoryEntry child in directoryEntry.Children) {

.

        if (child.SchemaClassName == "User") {

.

            PropertyCollection props = child.Properties;

.

            userNames += child.Name + "{" + child.Guid + "}" + Environment.NewLine;

.

When the data to receive is larger than the specified in 'prefmaxlen', an error code 234 is returned. You can pass 0xFFFFFFFF (which required the change from int to UInt32) in this parameter and then the needed amount of memory will be allocated.

.

            get { return this._ErrorMessage; }

.

    public bool AccountGetFullName(string MachineName, string AccountName, ref string FullName)

.

            if (MachineName.Length == 0 )

.

                throw new ArgumentException("Machine Name is required");

.

                int lngReturn = NetUserGetInfo(MachineName, AccountName, 10, out bufPtr ) ;

.

    Public Function AccountGetFullName(ByVal MachineName As String, ByVal AccountName As String, ByRef FullName As String) As Boolean

.

    If MachineName.Length = 0 Then

.

        Throw New ArgumentException("MachineName is Required")

.

        Dim lngReturn As Integer = NetUserGetInfo(MachineName, AccountName, 10, bufPtr)

.

The prefmaxlen parameter is DWORD, changed it to UInt32. This was already done for the netusergetgroups http://www.pinvoke.net/default.aspx/netapi32.netusergetgroups. Otherwise MAX_PREFERRED_LENGTH could not be passed which is defined as (DWORD)-1.

.

            // Creates a new wrapper for the local machine

.

            // Disposes of this wrapper

.

            public void Dispose() { GC.SuppressFinalize(this); }

.

            // Creates a new wrapper for the local machine

.

            // Disposes of this wrapper

.

            public void Dispose() { GC.SuppressFinalize(this); }

.

uint lngReturn = NetUserModalsGet(@"\\" + Environment.MachineName, 0, out bufPtr);

.

    uint lngReturn = NetUserModalsGet(@"\\" + Environment.MachineName, 0, out bufPtr);

.

NetSetupMachine,

.

NetSetupDnsMachine}

.

Most useful NameType's are 1 and 3 which will allow you to see if the name is in use.

.
Summary
The NetWkstaUserEnum function lists information about all users currently logged on to the workstation. This list includes interactive, service and batch logons.
.

WMI can do this sort of thing (the System.Management namespace in .Net 2.0)

.

If you want to find the user logged in to the workstation, consider instead a WMI query ("select UserName from Win32_ComputerSystem"), which has certain advantages (runs faster, less ambigious results, doesn't require Interop if using .Net 2.0 System.Management namespace, etc.)

.

* On Windows 8+ when users log in with a MicrosoftAccount the username is returned like "MicrosoftAccount\user.email@thedomain.com" rather than the ID. This means for example that it won't match their directory name in C:\Users.

.

        //this.listView1.Items.Clear();

.

        } while (nStatus == ERROR_MORE_DATA);

.

        string host = Environment.MachineName;

Cut off search results after 60. Please refine your search.


 
Access PInvoke.net directly from VS: