C# program won't launch when running as non-admin - c#

First off, I don't have any C# skills or experience. A friend of mine took a couple classes in college and was able to give me what I've got so far in this C# program.
I asked my friend to create a program that would look at WMI for the current logged on user's full name, then look at the RegisteredOwner value. If the full name is the same as the RegisteredOwner then the program quits (all silent), if the full name is different than the RegisteredOwner then the program would launch a form with some text and a yes/no option. If the user clicks yes, then the program sets the RegisteredOwner value to the logged on users full name, and if they click no, the program quits.
He delivered exactly what I asked for; however, it only runs if ran by a user with local admin rights and unfortunately, in my environment, no user is a local admin on their machine. When I presented the issue to him, he wasn't sure what he could do to resolve the problem, and after looking into this all day, I'm afraid there isn't much that can be done to resolve the issue and allow the program to be launched using the local users permissions.
So my question for you is do you know of a different way we could go with this program that would allow it to be run by a user without local admin rights? I would like to have the executable stored somewhere locally on the PC and then it in the startup items list of having something in the startup items list launch it. Maybe there's a way I can use a executable that works with non-local admin rights and then have it work with a windows service that's running under the System account?
When ran by a non local admin, nothing happens when you launch the script.
Below is the code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Management;
using System.Security.Principal;
using Microsoft.Win32;
using System.Threading;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
bool compare;
public Form1()
{
InitializeComponent();
if (PreLoad())
compare = true;
else
{
this.Text = GetUser();
compare = false;
}
}
private bool PreLoad()
{
string temp = GetCaption(GetUser());
RegistryKey regKey1 = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion");
string keyString = regKey1.GetValue("RegisteredOwner").ToString();
if (temp == keyString)
return true;
else
return false;
}
private void btnYes_Click(object sender, EventArgs e)
{
MessageBox.Show("Are you sure?", "Confirmation", MessageBoxButtons.OKCancel);
string temp = GetCaption(GetUser());
DoRegistryEdit(temp);
lblShowAll.Text = "-Successfully registered the machine to: " + temp + " -";
//Refreshes the screen so that the status message displays
this.Refresh();
Thread.Sleep(5000);
this.Close();
}
private void btnNo_Click(object sender, EventArgs e)
{
//MessageBox.Show("Better change computers then!");
this.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
if (compare)
this.Close();
}
public string GetCaption(string userName)
{
String QueryStringTemp = "Select * from Win32_NetworkLoginProfile where Caption = '" + userName + "'";
System.Management.ObjectQuery oQuery = new ObjectQuery(QueryStringTemp);
ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oQuery);
ManagementObjectCollection oReturnCollection = oSearcher.Get();
string capturedResults = "";
foreach (ManagementObject oReturn in oReturnCollection)
{
capturedResults += oReturn["FullName"].ToString();
}
return capturedResults;
}
public string GetUser()
{
System.Management.ObjectQuery oQuery = new ObjectQuery("Select * from Win32_ComputerSystem");
ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oQuery);
ManagementObjectCollection oReturnCollection = oSearcher.Get();
string capturedResults = "";
foreach (ManagementObject oReturn in oReturnCollection)
{
capturedResults += oReturn["UserName"].ToString();
}
int hold = capturedResults.IndexOf("\\");
capturedResults = capturedResults.Substring(hold + 1);
return capturedResults;
}
public void DoRegistryEdit(string name)
{
RegistryKey masterKey = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion");
if (masterKey == null)
MessageBox.Show("Null Master Key!");
else
{
try
{
masterKey.SetValue("RegisteredOwner", name);
}
catch (Exception ex)
{
MessageBox.Show("Uh OH!" + ex);
}
finally
{
masterKey.Close();
}
}
}
}
}
Any advice and suggestions would be appreciated!

WMI is the killer here. I suppose the whole "Management" part of WMI forces it to run in the admin space.
I found this resource on the Web:
http://skysigal.xact-solutions.com/Blog/tabid/427/EntryId/417/C-Compact-Framework-Getting-the-Registered-Owner.aspx
I tested it out to see that it worked respectably well on my Win7 X86 box. Judging from other sources on the web, this should be good for most recent versions of Windows, including several mobile editions.
Good luck!

Related

How to get apps(processes) per user on a terminal server? [duplicate]

I'm trying to get a list of processes currently owned by the current user (Environment.UserName). Unfortunately, the Process class doesn't have any way of getting the UserName of the user owning a process.
How do you get the UserName of the user which is the owner of a process using the Process class so I can compare it to Environment.UserName?
If your solution requires a pinvoke, please provide a code example.
Thanks, your answers put me on the proper path. For those who needs a code sample:
public class App
{
public static void Main(string[] Args)
{
Management.ManagementObjectSearcher Processes = new Management.ManagementObjectSearcher("SELECT * FROM Win32_Process");
foreach (Management.ManagementObject Process in Processes.Get()) {
if (Process["ExecutablePath"] != null) {
string ExecutablePath = Process["ExecutablePath"].ToString();
string[] OwnerInfo = new string[2];
Process.InvokeMethod("GetOwner", (object[]) OwnerInfo);
Console.WriteLine(string.Format("{0}: {1}", IO.Path.GetFileName(ExecutablePath), OwnerInfo[0]));
}
}
Console.ReadLine();
}
}
The CodeProject article How To Get Process Owner ID and Current User SID by Warlib describes how to do this using both WMI and using the Win32 API via PInvoke.
The WMI code is much simpler but is slower to execute. Your question doesn't indicate which would be more appropriate for your scenario.
You will have a hard time getting the username without being an administrator on the computer.
None of the methods with WMI, through the OpenProcess or using the WTSEnumerateProcesses will give you the username unless you are an administrator. Trying to enable SeDebugPrivilege etc does not work either. I have still to see a code that works without being the admin.
If anyone know how to get this WITHOUT being an admin on the machine it is being run, please write how to do it, as I have not found out how to enable that level of access to a service user.
You might look at using System.Management (WMI). With that you can query the Win32_Process tree.
here is the MS link labelled "GetOwner Method of the Win32_Process Class"
Props to Andrew Moore for his answer, I'm merely formatting it because it didn't compile in C# 3.5.
private string GetUserName(string procName)
{
string query = "SELECT * FROM Win32_Process WHERE Name = \'" + procName + "\'";
var procs = new System.Management.ManagementObjectSearcher(query);
foreach (System.Management.ManagementObject p in procs.Get())
{
var path = p["ExecutablePath"];
if (path != null)
{
string executablePath = path.ToString();
string[] ownerInfo = new string[2];
p.InvokeMethod("GetOwner", (object[])ownerInfo);
return ownerInfo[0];
}
}
return null;
}
You'll need to add a reference to System.Management.dll for this to work.
Here's what I ended up using. It works in .NET 3.5:
using System.Linq;
using System.Management;
class Program
{
/// <summary>
/// Adapted from https://www.codeproject.com/Articles/14828/How-To-Get-Process-Owner-ID-and-Current-User-SID
/// </summary>
public static void GetProcessOwnerByProcessId(int processId, out string user, out string domain)
{
user = "???";
domain = "???";
var sq = new ObjectQuery("Select * from Win32_Process Where ProcessID = '" + processId + "'");
var searcher = new ManagementObjectSearcher(sq);
if (searcher.Get().Count != 1)
{
return;
}
var process = searcher.Get().Cast<ManagementObject>().First();
var ownerInfo = new string[2];
process.InvokeMethod("GetOwner", ownerInfo);
if (user != null)
{
user = ownerInfo[0];
}
if (domain != null)
{
domain = ownerInfo[1];
}
}
public static void Main()
{
var processId = System.Diagnostics.Process.GetCurrentProcess().Id;
string user;
string domain;
GetProcessOwnerByProcessId(processId, out user, out domain);
System.Console.WriteLine(domain + "\\" + user);
}
}

How to authenticate using Active Directory in Winforms/C#?

I need to implement authentication using Active Directory for my Winforms application.
I know that it is possible to get current Windows user credential like this:
AppDomain currentDomain = AppDomain.CurrentDomain;
// Set the principal policy to WindowsPrincipal.
currentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
But I need that system asks user to either:
select logged in credentials => this would be possible with PrincipalPolicy.WindowsPrincipal I guess
choose to enter different credentials in Windows login form (not in my application) => how can I get this working?
P.S. I know it is possible to send username/password like it is described here:
Validate a username and password against Active Directory?
but I don't want to have user credentials going through my application because off security risks
I found out also this project in CodeProject.com on how to authenticate against Active Directory using LDAP, but this also requires entering user credentials in my application...
I know that there is also Active Directory Federated Services, but as far as I know it is for Web based authentication...
Any solutions for desktop authentication against Active Directory?
Here is a method I wrote in VB.NET in the past, and converted to C# for you.
use System.DirectoryServices namespace (you need to make a reference) in order to check credentials of user against DC(LDAP) server in your network (windows network of course).
clarification: this method was requested by our company security department for circumstances that user need to log in to company software from a colleague computer. i recommend (for security reasons) to require from your IT department to add all users to a specific active directory group and check also if the user is a member of this AD group, also record every local ip address that connects to the software.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.DirectoryServices;
namespace WindowsFormsApplication15
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
if (IsAuthenticated("YOUR DOMAIN", "USERNAME", "PASSWORD") == false)
{
// not exist in active directory!
}
else
{
// user is exist in active directory
}
}
private string _path { get; set; }
private string _filterAttribute { get; set; }
public bool IsAuthenticated(string domain, string username, string pwd)
{
string domainAndUsername = domain + "\\" + username;
DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);
try
{
object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if ((result == null))
{
return false;
}
_path = result.Path;
_filterAttribute = result.Properties["cn"][0].ToString();
}
catch (Exception ex)
{
return false;
}
return true;
}
}
}

Detecting USB to RS232 converter when connecting or disconnected

After much head scratching I managed to find the com port number of the USB to RS232 converters on my system. I have 15 in the present system. What I now need to do is detect when one is connected or disconnected so that I can update my table. I can work out how to detect a USB Storage device but the same does not work for USB to RS232 converters. Does anyone have any idea on how I can detect this please?
Here is the code snippet I use to work out the com ports in use by the converters
private void btn_tst2_Click(object sender, EventArgs e)
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_PnPEntity WHERE ClassGuid=\"{4d36e978-e325-11ce-bfc1-08002be10318}\"");
foreach (ManagementObject queryObj in searcher.Get())
{
rtxbx_output.AppendText(queryObj["Name"].ToString() +"\r");
}
}
You can make some sort of Thread or Task which queries the array returned from the method System.IO.Ports.SerialPort.GetPortNames(): when this array changes, or a new element is added, it means that a new serial port have been connected to the system.
Of course, it will return every serial port on your system, but then you can choose which of them are USB-RS232 converters with your code snippet.
You can make use of MSSerial_PortName Please find the snippet.
Note: This is not a working code, you have to make changes as per your requirement.
private void btn_tst2_Click(object sender, EventArgs e)
{
// connection to WMI rather than cimv2 namespace
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\WMI",
"select * from MSSerial_PortName");
foreach (ManagementObject queryObj in searcher.Get())
{
queryObj["Active"]; // status
queryObj["InstanceName"];
queryObj["PortName"]; // port number
}
}
After much frustration I finally worked out how to achieve what I needed. I post the answer in case it gives a pointer to anyone in the future stuck in the same area. I include comments in the code. What I get at the end is a list of all the Com Ports and this is refreshed when one leaves or joins. The file dbt.h is found on your PC.
To make the code below work just make a solution with a Rich text box and two buttons.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Management; //used to perform WMI queries
using System.Threading;
using System.Runtime.InteropServices; // needed for marshalling
namespace MissionControl
{
public partial class Control : Form
{
public Control()
{
InitializeComponent();
}
// WndProc = Window Procedures: Every window has an associated window procedure — a function that processes all messages sent
// or posted to all windows of the class. All aspects of a window's appearance and behavior depend on the window procedure's
// response to these messages. see https://msdn.microsoft.com/en-us/library/ms632593%28v=vs.85%29.aspx
protected override void WndProc(ref Message m)
{
//you may find these definitions in dbt.h
const int WM_DEVICECHANGE = 0x0219; // in dbt.h, BroadcastSpecialMessage constants.
const int DBT_DEVICEARRIVAL = 0x8000; // system detected a device arrived see dbt.h
const int DBT_DEVICEREMOVECOMPLETE = 0x8004; //system detected a device removal see dbt.h
const int DBT_DEVTYP_PORT = 0x00000003; // serial, parallel in dbt.h
switch (m.Msg)
{
case WM_DEVICECHANGE:
switch (m.WParam.ToInt32())
{
case DBT_DEVICEARRIVAL:
{
// Get the DBT_DEVTYP* as defined in dbt.h
// We are looking for DBT_DEVTYP_PORT value = 3 which is Serial port
int devTypeA = Marshal.ReadInt32(m.LParam, 4);
if (devTypeA == DBT_DEVTYP_PORT)
{
rchtxbx_output.SelectedText = string.Empty;
rchtxbx_output.SelectionFont = new Font(rchtxbx_output.SelectionFont, FontStyle.Bold);
rchtxbx_output.SelectionColor = Color.Lime;
rchtxbx_output.AppendText("\rSerial Port Connected\r\rList of Current Ports\r");
}
else
{
// We should never get in here but just in case do somethign rather than fall over
rchtxbx_output.SelectedText = string.Empty;
rchtxbx_output.SelectionFont = new Font(rchtxbx_output.SelectionFont, FontStyle.Bold);
rchtxbx_output.SelectionColor = Color.Red;
rchtxbx_output.AppendText("Non-Serial Port Connected\r");
}
//To prevent cross threading we will start the function call in its own thread
// Create the thread object, passing in GetPortNum
//ThreadA is the arrival thread (just connected)
Thread ThreadA = new Thread(new ThreadStart(GetPortNum));
// Start the thread via a ThreadStart delegate
ThreadA.Start();
}
break;
case DBT_DEVICEREMOVECOMPLETE:
{
// Get the DBT_DEVTYP* as defined in dbt.h
// We are looking for DBT_DEVTYP_PORT value = 3 which is Serial port
int devTypeD = Marshal.ReadInt32(m.LParam, 4);
if (devTypeD == DBT_DEVTYP_PORT)
{
rchtxbx_output.SelectedText = string.Empty;
rchtxbx_output.SelectionFont = new Font(rchtxbx_output.SelectionFont, FontStyle.Bold);
rchtxbx_output.SelectionColor = Color.Lime;
rchtxbx_output.AppendText("\rSerial Port Disconnected\r\rList of Current Ports\r");
}
else
{
// We should never get in here but just in case do something rather than fall over
rchtxbx_output.SelectedText = string.Empty;
rchtxbx_output.SelectionFont = new Font(rchtxbx_output.SelectionFont, FontStyle.Bold);
rchtxbx_output.SelectionColor = Color.Red;
rchtxbx_output.AppendText("Non-Serial Port Disconneted\r");
}
//To prevent cross threading we will start the function call in its own thread
// Create the thread object, passing in GetPortNum
//ThreadD is the departure thread (disconnected)
Thread ThreadD = new Thread(new ThreadStart(GetPortNum));
// Start the thread via a ThreadStart delegate
ThreadD.Start();
}
break;
}
break;
}
//we detect the media arrival event
base.WndProc(ref m);
}
private void btn_close_Click(object sender, EventArgs e)
{
this.Close();
}
private void btn_clr_Click(object sender, EventArgs e)
{
rchtxbx_output.Clear();
}
private void GetPortNum()
{
//Windows Management Instrumentation (WMI) consists of a set of extensions to the Windows Driver Model that provides an
//operating system interface through which instrumented components provide information and notification.
// To work out the WMI to use, get the tool https://www.microsoft.com/en-us/download/details.aspx?id=8572
//GUID (or UUID) is an acronym for 'Globally Unique Identifier' (or 'Universally Unique Identifier'). It is a 128-bit
//integer number used to identify resources. The term GUID is generally used by developers working with Microsoft
//technologies, while UUID is used everywhere else.
// Get the list of ClassGUID from https://msdn.microsoft.com/en-us/library/windows/hardware/ff553426%28v=vs.85%29.aspx
string comportnum = "";
int textStart = 0;
char[] textEnd = { ')' };
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_PnPEntity WHERE ClassGuid=\"{4d36e978-e325-11ce-bfc1-08002be10318}\"");
foreach (ManagementObject queryObj in searcher.Get())
{
comportnum = queryObj["Name"].ToString(); // Get the name of the comm port
//Format the string to extract the comport number only
textStart = comportnum.IndexOf("(COM");
comportnum = comportnum.Remove(0, textStart + 4).TrimEnd(textEnd);
//To prevent cross threading use Invoke. We are writing to a control created in another thread.
rchtxbx_output.Invoke(new EventHandler(delegate
{
rchtxbx_output.SelectedText = string.Empty;
rchtxbx_output.SelectionFont = new Font(rchtxbx_output.SelectionFont, FontStyle.Bold);
rchtxbx_output.SelectionColor = Color.Lime; //set font colour
rchtxbx_output.AppendText("Comm Port = " + comportnum + "\r"); //add some text
rchtxbx_output.ScrollToCaret(); // move cursor to the end
}));
}
}
}
}

Active Directory move a user to a different OU

I'm working on a program that will automate the separation process for users leaving our network. One of the tasks it performs is moving the user account from the OU it is in, to a Former Employees OU. I've been having problems with this step even though I've not had any issues doing other processes with DirectoryServices. Here's my code thus far (note: I know I need to stop catching and eating all exceptions. This will be addressed and corrected before release. Any advice on which exceptions I should catch and which I should not would be appreciated too):
private const string AD_DOMAIN_NAME = "domain.com";
private const string AD_NEW_PASSWORD = "TestPassword123";
private const string AD_FORMER_EMPLOYEES_OU = "LDAP://OU=Former Employees,DC=domain,DC=com";
static DirectoryEntry CreateDirectoryEntry(string connectionPath,
string adUserName, string adPassword)
{
DirectoryEntry ldapConnection = null;
try
{
ldapConnection = new DirectoryEntry(AD_DOMAIN_NAME, adUserName, adPassword);
ldapConnection.Path = connectionPath;
ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
}
catch (Exception ex)
{
MessageBox.Show("Exception Caught in createDirectoryEntry():\n\n" + ex.ToString());
}
return ldapConnection;
}
private void btnProcessSeparation_Click(object sender, EventArgs e)
{
if (cboOffice.SelectedItem != null && lstUsers.SelectedItem != null)
{
string userOU = cboOffice.SelectedItem.ToString();
string userName = lstUsers.SelectedItem.ToString();
string userDn = "LDAP://OU=" + userOU + ",OU=Employees,DC=domain,DC=com";
using (DirectoryEntry ldapConnection = CreateDirectoryEntry(userDn))
{
using (DirectorySearcher searcher = CreateDirectorySearcher(ldapConnection,
SearchScope.OneLevel, "(samaccountname=" + userName + ")", "samaccountname"))
{
SearchResult result = searcher.FindOne();
if (result != null)
{
using (DirectoryEntry userEntry = result.GetDirectoryEntry())
{
if (userEntry != null)
{
using (DirectoryEntry formerEmployees = CreateDirectoryEntry(
AD_FORMER_EMPLOYEES_OU))
{
userEntry.MoveTo(formerEmployees); // This line throws an DirectoryServicesCOMException.
}
userEntry.CommitChanges();
userEntry.Close();
MessageBox.Show("Separation for {0} has completed successfully.", userName);
}
}
}
}
}
}
else
{
MessageBox.Show("Error, you did not select an OU or a user. Please try again.");
}
}
The above code works just fine until the userEntry.MoveTo(formerEmployees); line. That line throws a DirectoryServicesCOMException with the additional information saying An invalid dn syntax has been specified. It is strange because I'm using the same format as the other DirectoryEntry's that work just fine. I've added a break point and confirmed that formerEmployees is set to: LDAP://OU=Former Employees,DC=domain,DC=com. I copied everything after LDAP:// directly from the OU's distinguishedName attribute in Active Directory to make sure it was correct.
Is the space in the OU name causing the problem? I got this to work once just fine and moved on to the other tasks and must have changed something that broke this. I've been looking at the code too much I think and just can't seem to see why it thinks I'm sending an invalid dn.
Thanks for any and all help!
Hope this helps:
DirectoryEntry eLocation = Conexion.Conectar(Localitation);
DirectoryEntry nLocation =Conexion.Conectar(NewLocalitation);
string newName = eLocation.Name;
eLocation.MoveTo(nLocation, newName);
nLocation.Close();
eLocation.Close();
After #David pointed me in the right direction of making sure I had the correct permissions to the OU, I discovered the problem. I added an overloaded CreateDirectoryEntry method that uses the username and password (which is what I put in the code above). However, if you notice in the code above, I call the method that only takes the connection path.
Thanks for the help #David!

Programmatically add Local User to a Local Group

I am doing a C# application targeting WinXP, Vista, and 7 Operating Systems.
One feature is, I can Add, Remove, Modify the Group set to a user programmatically.
Can I ask for help how to make this happen?
Will it be possible to do this in WMI? My codes mainly using WMI to get the users..
Currently am using Windows7
I am trying to test this code
DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName + ",Computer");
localMachine.Properties["member"].Add("Chevi");
localMachine.CommitChanges();
localMachine.Close();
and it's spitting this error
The directory property cannot be found in the cache.
I tried enumerating the Property collection and I got this
OperatingSystem
OperatingSystemVersion
Owner
Division
ProcessorCount
Processor
Name
If you're using local groups, you can do this by calling the system net command. For example, to add a user to a group, you'd call:
net localgroup MyGroup /add SomeUser
Type net help localgroup at a command prompt for more info.
You can also do this using WMI. This is VBScript but can be adapted to .NET or your preferred programming toolkit:
Dim oComputer
Computer = "computername"
Groupname = "Administrators"
ObjectToAdd = "Administrator"
' Bind to the computer.
Set oComputer = GetObject("WinNT://" & Computer & ",computer")
' get group object
Dim oGroup
Set oGroup = oComputer.GetObject("group", GroupName)
' Add the user object to the group.
oGroup.Add "WinNT://" & Computer & "/" & ObjectToAdd
Credit: Matt Hickman, http://www.tech-archive.net/Archive/WinXP/microsoft.public.windowsxp.wmi/2004-04/0007.html
I have also developed one windows application on Visual Studio 2010, using C#. This is a working version of the program, which will add an existing user to a particular group.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.DirectoryServices;
namespace Utility_Add_User_To_Group {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void btn_Add_Click(object sender, EventArgs e) {
string usr, grp;
usr = txt_UserName.Text;
grp = txt_GroupName.Text;
add(usr, grp);
groupBox2.Visible=true;
}
private void add(string usr, string grp) {
bool flagUsr, flagGrp;
try {
DirectoryEntry AD = new DirectoryEntry("WinNT://" +Environment.MachineName + ",computer");
DirectoryEntry group, user;
group = AD.Children.Find(grp, "group");
user = AD.Children.Find(usr, "user");
if (user != null) {
label3.Text += "User Name Exists!!!";
flagUsr = true;
} else {
label3.Text += "Sorry, No Such User Name Found!!!";
flagUsr = false;
}
if (group != null) {
label4.Text += "Group Exists!!!";
flagGrp = true;
} else {
label4.Text += "Sorry, Group Does Not Exists!!!";
flagGrp= false;
}
if(flagGrp == true && flagUsr == true) {
group.Invoke("Add", new object[] { user.Path.ToString() });
label5.Text += "Congratulations!!! User has been added to the group";
} else {
label5.Text += "Error Happened!!! User could not be added to the group!!!";
}
} catch (Exception e) {
label6.Text +=e.Message.ToString();
label6.Visible= true;
}
}
private void btn_Clear_Click(object sender, EventArgs e) {
normal();
}
private void normal() {
txt_GroupName.Text="";
txt_UserName.Text="";
txt_UserName.Focus();
groupBox2.Visible=false;
}
}
}
NetUserAdd to create a user
NetGroupAdd to create a group
NetGroupAddUser to add a user to a group
NetGroupDelUser to remove an user form a group
NetLocalGroupAdd to create a local group
NetLocalGroupAddMembers to add users to a local group
etc etc

Categories

Resources