I'm using my broadband internet through Wan Miniport (PPPOE) connection and I've Windows 7 as my OS. I would like to disconnect the internet connection through C#. I searched a lot over the internet but I'm not sure which methodology (WMI, WinInet etc) suits my connection.
I will be reconnecting through another software later, hence my requirement is just to disconnect from the internet rather totally disabling it permanently.
Kindly please give some solution & code to implement this.
?
Use WMI:
C#:
var wmiQuery = new SelectQuery("SELECT * FROM Win32_NetworkAdapter " +
"WHERE NetConnectionId != null " +
"AND Manufacturer != 'Microsoft' ");
using (var searcher = new ManagementObjectSearcher(wmiQuery))
{
foreach (ManagementObject item in searcher.Get())
{
if (((String)item["NetConnectionId"]) == "Local Area Connection")
{
using (item)
{
item.InvokeMethod("Disable", null);
}
}
}
}
VB:
Dim wmiQuery = New SelectQuery("SELECT * FROM Win32_NetworkAdapter " & "WHERE NetConnectionId != null " & "AND Manufacturer != 'Microsoft' ")
Using searcher = New ManagementObjectSearcher(wmiQuery)
For Each item As ManagementObject In searcher.[Get]()
If DirectCast(item("NetConnectionId"), [String]) = "Local Area Connection" Then
Using item
item.InvokeMethod("Disable", Nothing)
End Using
End If
Next
End Using
Related
I'm using the following code to get my drive serial number. It's working fine with Windows 7, 8, 8.1, and 10 Professional, but I'm getting an error on Windows 10 Home.
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
foreach (ManagementObject wmi_HD in searcher.Get())
{
if (wmi_HD["SerialNumber"] == null)
hddId = null;
else
hddId = wmi_HD["SerialNumber"].ToString();
}
I'm getting
System.NullReferenceException : Object reference not set to an instance of an object.
Does anyone know why? What do I need to do to get the serial number in this case?
One more question: if I boot the OS from my pendrive, will this code work? How could I know that the OS is running from a pendrive or disk or any other resource?
When I go to the Device Manager, I see this:
I am adding this as an answer because it can save lot of time while debugging scenarios like System.NullReferenceException in WMI.
Windows+R (run command)
Type wbemtest
And connect to the machine for which you want to fetch information. Fire the query for Win32_DiskDrive and check the output for properties that you can fetch.
This is what I'm using on Windows 10 v1809:
using System;
using System.Management;
namespace GetSerialNo
{
class Program
{
static void Main(string[] args)
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
foreach (ManagementObject info in searcher.Get())
{
Console.WriteLine("DeviceID: " + info["DeviceID"].ToString());
Console.WriteLine("Model: " + "Model: " + info["Model"].ToString());
Console.WriteLine("Interface: " + "Interface: " + info["InterfaceType"].ToString());
Console.WriteLine("Serial#: " + "Serial#: " + info["SerialNumber"].ToString());
}
Console.ReadLine();
}
}
}
For details please see http://csharphelper.com/blog/2017/10/get-hard-drive-serial-number-c/
For the associated link Get Hard disk serial Number given by #ADreNaLiNe-DJ I wasn't able to find the required assembly reference for HardDrive hd = new HardDrive();
I have 3 wifi at my home, in some rooms I have signal from the 3 routers and If I'm connected to one windows 10 won't change to the strongest wifi. I would like to know a working way to disable and enable wifi that works in windows 10.
My code doesn't work in widnows 10.
SelectQuery wmiQuery = new SelectQuery("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionId != NULL");
ManagementObjectSearcher searchProcedure = new ManagementObjectSearcher(wmiQuery);
foreach (ManagementObject item in searchProcedure.Get())
{
if (((string)item["NetConnectionId"]) == "Local Network Connection")
{
item.InvokeMethod("Disable", null);
}
}
I'm testing Native Wifi with some success, I'll post more results soon
As shown below in the picture, when I tried to retrieve all printers, I got only 2 printers.
Is there a way to return all printers using either PowerShell WMI or C#(so that I can translate it in powershell)?
I have tried System.Drawing.Printing.PrinterSettings.InstalledPrinters (refer to how to get the list of all printers in computer - C# Winform) but also displays only 2 entries.
Simply,
via System.Drawing.Printing
foreach (String printer in PrinterSettings.InstalledPrinters)
{
Console.WriteLine(printer.ToString()+Environment.NewLine);
}
via WMI
public static void AvailablePrinters()
{
oManagementScope = new ManagementScope(ManagementPath.DefaultPath);
oManagementScope.Connect();
SelectQuery oSelectQuery = new SelectQuery();
oSelectQuery.QueryString = #"SELECT Name FROM Win32_Printer";
ManagementObjectSearcher oObjectSearcher =
new ManagementObjectSearcher(oManagementScope, #oSelectQuery);
ManagementObjectCollection oObjectCollection = oObjectSearcher.Get();
foreach (ManagementObject oItem in oObjectCollection)
{
Console.WriteLine("Name : " + oItem["Name"].ToString()+ Environment.NewLine);
}
}
via PowerShell
Get-WMIObject -class Win32_Printer -computer $printserver | Select Name,DriverName,PortName
For more information, please check this article & WMI Printer Class
Recently I am making a system monitoring tool. For that I need a class to monitor print job.
Such as when a print started, is it successful or not, how many pages.
I know that I can do it using winspool.drv. But dont how. I've searched extensively but having no luck. Any code/suggestion could be very helpful.
Thanks.
Well I don't know about the winspool.drv, but you can use the WMI to get the status of the printer. Here is an example of the using Win32_Printer.
PrintDialog pd = new PrintDialog();
pd.ShowDialog();
PrintDoc.PrinterSettings = pd.PrinterSettings;
PrintDoc.PrintPage += new PrintPageEventHandler(PrintDoc_PrintPage);
PrintDoc.Print();
object status = Convert.ToUInt32(9999);
while ((uint)status != 0) // 0 being idle
{
ManagementObjectSearcher mos = new ManagementObjectSearcher("select * from Win32_Printer where Name='" + pd.PrinterSettings.PrinterName + "'");
foreach (ManagementObject service in mos.Get())
{
status = service.Properties["PrinterState"].Value;
Thread.Sleep(50);
}
}
If you don't use the PrintDialog object (to choose a printer) you can run the WMI query and it will return all the printers in the system.
How can I detect if SQL is installed on the local machine using C#? Is it possible to check a remote machine?
You've got several ways to do it:
SmoApplication.EnumAvailableSqlServers()
SqlDataSourceEnumerator.Instance
Direct access to system registry
Direct access isn't the recommended solution by MS, because they can change keys/paths. But the other solutions fails providing instances on 64-bit platforms.
Therefore I prefer to check SQL Server instances in System Registry. Doing that, keep in mind the difference in Registry access between x86 and x64 platforms. Windows 64-bit stores data in different parts of system registry and combines them into views. So using RegistryView (available since .NET 4) is essential.
using Microsoft.Win32;
RegistryView registryView = Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32;
using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView))
{
RegistryKey instanceKey = hklm.OpenSubKey(#"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL", false);
if (instanceKey != null)
{
foreach (var instanceName in instanceKey.GetValueNames())
{
Console.WriteLine(Environment.MachineName + #"\" + instanceName);
}
}
}
If you are looking for 32-bit instances on a 64-bit OS (pretty weird, but possible), you will need to look:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Microsoft SQL Server
You can check registry path
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\InstalledInstances
For an example of code that does similar work, see this quesion how-to-get-sql-server-installation-path-programatically
Please also see MSDN: File Locations for Default and Named Instances of SQL Server for more details on registry keys used by SQL Server.
We check the registry for that
Registry.GetValue(#"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\MSSQLServer\CurrentVersion", ", "0.0.0.0");
You could use the System.Management namespace to check for the existence of SQL Server in the server's running services.
You will need SQL 2005 Backwards Compatibility redist.
See: How to Connect to Sqlserver2008 using SMO any workaround has to be done?
using Microsoft.SqlServer.Management.Smo;
DataTable dt = SmoApplication.EnumAvailableSqlServers(true);
string[] szSQLInstanceNames = new string[dt.Rows.Count];
StringBuilder szSQLData = new StringBuilder();
if (dt.Rows.Count > 0)
{
int i = 0;
foreach (DataRow dr in dt.Rows)
{
try
{
szSQLInstanceNames[i] = dr["Name"].ToString();
Server oServer;
oServer = new Server(szSQLInstanceNames[i]);
if (string.IsNullOrEmpty(dr["Instance"].ToString()))
{
szSQLInstanceNames[i] = szSQLInstanceNames[i] + "\\MSSQLSERVER";
}
szSQLData.AppendLine(szSQLInstanceNames[i] + " Version: " + oServer.Information.Version.Major + " Service Pack: " + oServer.Information.ProductLevel + " Edition: " + oServer.Information.Edition + " Collation: " + oServer.Information.Collation);
}
catch (Exception Ex)
{
szSQLData.AppendLine("Exception occured while connecting to " + szSQLInstanceNames[i] + " " + Ex.Message);
}
i++;
}
Note: if you just want to see if Default intance is installed or no just do:
Server oServer;
oServer = new Server(Environment.MAchineName);
if it does not throw an exception, the SQL exists.
Perhaps you'll find the following useful. Use first method to find about servers (local & network), then you can use the second to enumerate databases on each server.
using System;
using System.Collections.Generic;
using System.Data.Sql;
using System.Data;
using System.Data.SqlClient;
namespace Info.Data.Engine.SQLServer
{
public static class SQLServerHelper
{
public static List<String> EnumerateServers()
{
var instances = SqlDataSourceEnumerator.Instance.GetDataSources();
if ((instances == null) || (instances.Rows.Count < 1)) return null;
var result = new List<String>();
foreach (DataRow instance in instances.Rows)
{
var serverName = instance["ServerName"].ToString();
var instanceName = instance["InstanceName"].ToString();
result.Add(String.IsNullOrEmpty(instanceName) ? serverName : String.Format(#"{0}\{1}", serverName, instanceName));
}
return result;
}
public static List<String> EnumerateDatabases(String connectionString)
{
try
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
var databases = connection.GetSchema("Databases");
connection.Close();
if ((databases == null) || (databases.Rows.Count < 1)) return null;
var result = new List<String>();
foreach (DataRow database in databases.Rows)
{
result.Add(database["database_name"].ToString());
}
return result;
}
}
catch
{
return null;
}
}
}
}
HTH,
Dejan
You could just open a connection to the machine and close it. If you throw an exception that's a decent sign. I realize it's not super clean but it'll get the job done.
Thanks a lot to Dejan Stanič.
And I wanted to add more search criteria:
Check if SQL Server 2008 is installed on local machine in .net sqlclient