Change Window Server 2012 R2 IP Address, Subnet mask, Gateway in C# - c#

I created c# console application to change IP Address, Subnet mask and Gateway.
It's work good on window 8.1 Enterprise but It not working on Window server 2012 R2. And this is my code.
public bool setIP(string ip_address, string subnet_mask)
{
ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
if ((bool)objMO["IPEnabled"])
{
try
{
ManagementBaseObject setIP;
ManagementBaseObject newIP = objMO.GetMethodParameters("EnableStatic");
newIP["IPAddress"] = new string[] { ip_address };
newIP["SubnetMask"] = new string[] { subnet_mask };
setIP = objMO.InvokeMethod("EnableStatic", newIP, null);
return true;
}
catch (Exception)
{
Console.WriteLine("Unable to set IP");
return false;
}
}
else
{
return false;
}
}
return false;
}
public bool setGateway(string gateway)
{
ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
if ((bool)objMO["IPEnabled"])
{
try
{
ManagementBaseObject setGateway;
ManagementBaseObject newGateway =
objMO.GetMethodParameters("SetGateways");
newGateway["DefaultIPGateway"] = new string[] { gateway };
newGateway["GatewayCostMetric"] = new int[] { 1 };
setGateway = objMO.InvokeMethod("SetGateways", newGateway, null);
return true;
}
catch (Exception)
{
Console.WriteLine("Unable to set Gateway");
return false;
}
}
}
return false;
}
Please, Give me some suggestion.

Related

How to set IP address of device connected to Host PC? C# Winform?

I have a Modbus TCP/IP to MODBUS RTU converter , which comes with a default IP of 192.168.0.1 . I need to develop a small c# Winform app to change this device's IP address to any desired IP address. How do I do that?.
You could do it with WMI (Windows Management Instrumentation).
First, you have to add the reference for System.Management to your Project.
Second, you need to find the NetworkInterface for your network connection by name:
using System.Net.NetworkInformation;
using System.Management;
public class NetworkManager
{
public static NetworkInterface GetNetworkInterface(string sName)
{
NetworkInterface NetInterface = null;
// Precondition
if (sName == "") return null;
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface ni in interfaces)
{
if (ni.Name == sName)
{
NetInterface = ni;
break;
}
}
return NetInterface;
}
Third, you have to create a ManagementObject for your NetworkInterface:
public static ManagementObject GetNetworkAdapterManagementObject(NetworkInterface NetInterface)
{
ManagementObject oMngObj = null;
// Precondition
if (NetInterface == null) return null;
string sNI = NetInterface.Id;
ManagementClass oMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection oMOC = oMC.GetInstances();
foreach (ManagementObject oMO in oMOC)
{
string sMO = oMO["SettingID"].ToString();
if (sMO == sNI)
{
// Found
oMngObj = oMO;
break;
}
}
return oMngObj;
}
Fours, you can set the ipadress with:
public static bool SetIPAdress(ManagementObject oMO, string[] saIPAdress, string[] saSubnetMask)
{
bool bErg = false;
try
{
// Precondition
if (oMO == null) return false;
if (saIPAdress == null) return false;
if (saSubnetMask == null) return false;
// Get ManagementBaseObject
ManagementBaseObject oNewIP = null;
oNewIP = oMO.GetMethodParameters("EnableStatic");
oNewIP["IPAddress"] = saIPAdress;
oNewIP["SubnetMask"] = saSubnetMask;
// Invoke
oMO.InvokeMethod("EnableStatic", oNewIP, null);
// Alles ok
bErg = true;
}
catch (Exception ex)
{
Console.WriteLine("SetIPAdress failed: " + ex.Message);
}
return bErg;
}
}
Now you can use it, for example in a button click event handler:
private void button1_Click(object sender, EventArgs e)
{
string sConn = "LAN-Verbindung";
NetworkInterface oNI = NetworkManager.GetNetworkInterface(sConn);
ManagementObject oMO = NetworkManager.GetNetworkAdapterManagementObject(oNI);
string sIPAdress = "192.168.1.1";
string sSubnetMask = "255.255.255.0";
string[] saIPAdress = {sIPAdress};
string[] saSubnetMask = {sSubnetMask};
if (NetworkManager.SetIPAdress(oMO, saIPAdress, saSubnetMask))
{
Console.WriteLine("Yes...");
}
}
Depending on the policies on your pc, may be you have to run the program as Administrator...

Get client machine's default printer when application is accessed through citrix

i have a windows application which insert client machine's default printer to database on application launch. It works perfectly in my solution. I use the following code to save this.
string GetDefaultPrinter()
{
string defaultprinter = "";
try
{
PrinterSettings settings = new PrinterSettings();
foreach (string printer in PrinterSettings.InstalledPrinters)
{
settings.PrinterName = printer;
if (settings.IsDefaultPrinter)
{
defaultprinter = printer;
string[] array_printer= defaultprinter.Split('\\');
defaultprinter= array_printer[3].ToString();
string query = string.Format("SELECT * from Win32_Printer WHERE Name LIKE '%{0}'", defaultprinter);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection coll = searcher.Get();
foreach (ManagementObject localprinter in coll)
{
foreach (PropertyData property in localprinter.Properties)
{
// Console.WriteLine(string.Format("{0}: {1}", property.Name, property.Value));
//MessageBox.Show(property.Name+"-"+ property.Value);
if (property.Name == "ShareName")
{
defaultprinter = property.Value.ToString().Trim();
}
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("defaltprinter- "+defaultprinter+"-" + ex.Message);
}
return defaultprinter;
}<br>
If I host this application in citrix, then what should I do to perform the same function?
regards,
Sivajith S.

Request Win32_ComputerSystem class remote

Does somebody have some example C# code about how objects from the Win32_ComputerSystem WMI class can be retrieved from a remote system using hostname, username and password?
Connecting:
try
{
rcOptions = new ConnectionOptions();
rcOptions.Authentication = AuthenticationLevel.Packet;
rcOptions.Impersonation = ImpersonationLevel.Impersonate;
rcOptions.EnablePrivileges = true;
rcOptions.Username = servername + #"\" + username;
rcOptions.Password = password;
mScope = new ManagementScope(String.Format(#"\\{0}\root\cimv2", servername), rcOptions);
mScope.Connect();
if (mScope.IsConnected == true) { MessageBox.Show("Connection Succeeded", "Alert"); } else { MessageBox.Show("Connection Failed", "Alert"); }
if (mScope.IsConnected == true) { lblConnectionStateWarning.Text = "Connected"; } else { lblConnectionStateWarning.Text = "Disconnected"; } //I have a label that displays connectionstate, you can leave that out
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
Getting query with method, loading into dictonary & returning into listview
private void FindWMI(string servername, string classSelection, ConnectionOptions rcOptions, ListView listView)
{
try
{
var dct = new Dictionary<string, string>();
List<ListViewItem> itemsList = new List<ListViewItem>();
oQuery = new ObjectQuery("select * from " + classSelection);
moSearcher = new ManagementObjectSearcher(mScope, oQuery);
moCollection = moSearcher.Get();
Invoke(new MethodInvoker(() =>
{
listView.Items.Clear();
}));
foreach (ManagementObject mObject in moCollection)
{
if (mObject != null)
{
foreach (PropertyData propData in mObject.Properties)
{
if (propData.Value != null && propData.Value.ToString() != "" && propData.Name != null && propData.Name != "")
dct[propData.Name] = propData.Value.ToString();
//Don't forget this, when the result is an array, you want all the strings in that array..
if (propData.Value is Array) { dct[propData.Name] = ""; foreach (string stringArray in (string[])propData.Value) { dct[propData.Name] += stringArray + "\n"; } }
}
}
}
foreach (KeyValuePair<string, string> listItem in dct)
{
ListViewItem lstItem = new ListViewItem(listItem.Key);
lstItem.SubItems.Add(listItem.Value);
itemsList.Add(lstItem);
}
Invoke(new MethodInvoker(() =>
{
listView.Items.AddRange(itemsList.ToArray());
}));
}
catch (Exception) { }
}

how to get logged on users with their status on remote machine

I'm looking for a way to get the users that are logged in on a remote machine. I would love to know if they are logged on localy or remotely, but most of all I MUST know their status.
I saw some answers on the net that are written in VB, but I need it in c#.
the solution given in markdmak answer here is looking like a good start, but it's in VB and it looks for remote sessions only.
I have this piece of code, which can be a start, but I would like to couple the LogonId to a username and to see its status:
string fqdn = ""; // set!!!
ConnectionOptions options = new ConnectionOptions();
options.EnablePrivileges = true;
// To connect to the remote computer using a different account, specify these values:
// these are needed in dev environment
options.Username = ConfigurationManager.AppSettings["KerberosImpersonationUser"];
options.Password = ConfigurationManager.AppSettings["KerberosImpersonationPassword"];
options.Authority = "ntlmdomain:" + ConfigurationManager.AppSettings["KerberosImpersonationDomain"];
ManagementScope scope = new ManagementScope("\\\\" + fqdn + "\\root\\CIMV2", options);
try
{
scope.Connect();
}
catch (Exception ex)
{
if (ex.Message.StartsWith("The RPC server is unavailable"))
{
// The Remote Procedure Call server is unavailable
// cannot check for logged on users
return false;
}
else
{
throw ex;
}
}
SelectQuery query = new SelectQuery("Select * from Win32_LogonSession");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection results = searcher.Get();
bool returnVal = false;
foreach (ManagementObject os in results)
{
try
{
if (os.GetPropertyValue("LogonId").ToString() != null && os.GetPropertyValue("LogonId").ToString() != "")
{
returnVal = true;
}
}
catch (NullReferenceException)
{
continue;
}
}
return returnVal;
}
What I really need and can't find, is a way of getting ALL users on a remote machine AND their status, meaning: Active, Disconnected, Logged-off, etc.
You can use the Win32_LogonSession WMI class filtering for the LogonType property with the value 2 (Interactive)
Try this sample
using System;
using System.Collections.Generic;
using System.Management;
using System.Text;
namespace GetWMI_Info
{
class Program
{
static void Main(string[] args)
{
try
{
string ComputerName = "remote-machine";
ManagementScope Scope;
if (!ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase))
{
ConnectionOptions Conn = new ConnectionOptions();
Conn.Username = "username";
Conn.Password = "password";
Conn.Authority = "ntlmdomain:DOMAIN";
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), Conn);
}
else
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);
Scope.Connect();
ObjectQuery Query = new ObjectQuery("SELECT LogonId FROM Win32_LogonSession Where LogonType=2");
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);
foreach (ManagementObject WmiObject in Searcher.Get())
{
Console.WriteLine("{0,-35} {1,-40}", "LogonId", WmiObject["LogonId"]);// String
ObjectQuery LQuery = new ObjectQuery("Associators of {Win32_LogonSession.LogonId=" + WmiObject["LogonId"] + "} Where AssocClass=Win32_LoggedOnUser Role=Dependent");
ManagementObjectSearcher LSearcher = new ManagementObjectSearcher(Scope, LQuery);
foreach (ManagementObject LWmiObject in LSearcher.Get())
{
Console.WriteLine("{0,-35} {1,-40}", "Name", LWmiObject["Name"]);
}
}
}
catch (Exception e)
{
Console.WriteLine(String.Format("Exception {0} Trace {1}", e.Message, e.StackTrace));
}
Console.WriteLine("Press Enter to exit");
Console.Read();
}
}
}
#RRUZ got me started but the Associators query did not work on remote machine with a lot of Win32_LoggedOnUser objects (don't know why). No results were returned.
I also needed remote Desktop sessions so I used LogonType "10" sessions and my ConnectionOptions were differents
I replaced the Associators query with WmiObject.GetRelationships("Win32_LoggedOnUser") and the speed increases by a lot and results were there.
private void btnUnleash_Click(object sender, EventArgs e)
{
string serverName = "serverName";
foreach (var user in GetLoggedUser(serverName))
{
dataGridView1.Rows.Add(serverName, user);
}
}
private List<string> GetLoggedUser(string machineName)
{
List<string> users = new List<string>();
try
{
var scope = GetManagementScope(machineName);
scope.Connect();
var Query = new SelectQuery("SELECT LogonId FROM Win32_LogonSession Where LogonType=10");
var Searcher = new ManagementObjectSearcher(scope, Query);
var regName = new Regex(#"(?<=Name="").*(?="")");
foreach (ManagementObject WmiObject in Searcher.Get())
{
foreach (ManagementObject LWmiObject in WmiObject.GetRelationships("Win32_LoggedOnUser"))
{
users.Add(regName.Match(LWmiObject["Antecedent"].ToString()).Value);
}
}
}
catch (Exception ex)
{
users.Add(ex.Message);
}
return users;
}
private static ManagementScope GetManagementScope(string machineName)
{
ManagementScope Scope;
if (machineName.Equals("localhost", StringComparison.OrdinalIgnoreCase))
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", "."), GetConnectionOptions());
else
{
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", machineName), GetConnectionOptions());
}
return Scope;
}
private static ConnectionOptions GetConnectionOptions()
{
var connection = new ConnectionOptions
{
EnablePrivileges = true,
Authentication = AuthenticationLevel.PacketPrivacy,
Impersonation = ImpersonationLevel.Impersonate,
};
return connection;
}

Set network configuration programmatically c#

I want to save my network adapter configuration and then to restore it on another computer. I use WMI to get my network configurations and i save it to the .txt file :
using (TextWriter tw = new StreamWriter(#"D:\\NetworkConfiguration.txt"))
{
if (tw != null)
{
ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
if (!(bool)objMO["ipEnabled"])
continue;
string[] ipaddresses = (string[])objMO["IPAddress"];
string[] subnets = (string[])objMO["IPSubnet"];
string[] gateways = (string[])objMO["DefaultIPGateway"];
tw.WriteLine("IpAdresses");
foreach (string sIP in ipaddresses)
tw.WriteLine(sIP);
tw.WriteLine("IpSubnets");
foreach (string sNet in subnets)
tw.WriteLine(sNet);
tw.WriteLine("Gateways");
foreach (string sGate in gateways)
tw.WriteLine(sGate);
// close the stream
tw.Close();
}
}
}
and then , when i want to set tcp/ip settings on another computer , i read the file's information :
using (TextReader tr = new StreamReader(#"D:\\NetworkConfiguration.txt"))
{
List<string> ipAddrr = new List<string>();
List<string> ipSubnet = new List<string>();
List<string> Gateway = new List<string>();
string line = tr.ReadLine();
while (line != null)
{
if (line.Equals("IpAdresses"))
{
ipAddrr.Add(tr.ReadLine());
ipAddrr.Add(tr.ReadLine());
}
if (line.Equals("IpSubnets"))
{
ipSubnet.Add(tr.ReadLine());
ipSubnet.Add(tr.ReadLine());
}
if (line.Equals("Gateways"))
{
Gateway.Add(tr.ReadLine());
}
line = tr.ReadLine();
}
setIP(ipAddrr.ToArray(), ipSubnet.ToArray(), Gateway.ToArray());
}
and set the new setting :
public void setIP(string[] IPAddress, string[] SubnetMask, string[] Gateway)
{
ManagementClass objMC = new ManagementClass(
"Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
if (!(bool)objMO["IPEnabled"])
continue;
try
{
ManagementBaseObject objNewIP = null;
ManagementBaseObject objSetIP = null;
ManagementBaseObject objNewGate = null;
objNewIP = objMO.GetMethodParameters("EnableStatic");
objNewGate = objMO.GetMethodParameters("SetGateways");
//Set DefaultGateway
objNewGate["DefaultIPGateway"] = Gateway ;
objNewGate["GatewayCostMetric"] = new int[] { 1 };
//Set IPAddress and Subnet Mask
objNewIP["IPAddress"] = IPAddress;
objNewIP["SubnetMask"] = SubnetMask;
objSetIP = objMO.InvokeMethod("EnableStatic", objNewIP, null);
objSetIP = objMO.InvokeMethod("SetGateways", objNewGate, null);
MessageBox.Show(
"Updated IPAddress, SubnetMask and Default Gateway!");
}
catch (Exception ex)
{
MessageBox.Show("Unable to Set IP : " + ex.Message);
}
}
}
but the problem is that when i check my tcp/ip configuration , it never changes.....
i dont understand how to get it work....
Take a look at this question - different method but should work ok.

Categories

Resources