Using Visual Studios RC 2017, using their template for a .NET Windows Form Application
Trying to get a list of usb devices from my computer, and stick it crudely into a rTextbox for a school project, using a function in System.Management called "GetUSBDevices()".
Attempting to do this using a function I know System.Management has, and that works while using in a Visual Studios C# Console Application Template,and for some reason It won't recognize the reference...
I've tried:
Adding System.Management as a reference through the solution explorer
reinstalling the System.Management Reference
calling the function directly from the library [ System.Management.GetUSBDevices(); ]
And nothing has worked so far...
Code That Doesn't Work:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Management; //ISSUE HERE!
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Manager
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void DisplayProcess()
{
richTextBox1.Clear();
Process[] plist = Process.GetProcesses();
foreach (Process p in plist)
{
richTextBox1.Text += "Process " + p.Id.ToString() + " : " + p.ProcessName.ToString() + "\n";
}
}
//-----------------------------------ISSUE HERE-----------------------------
//-----------------------------------ISSUE HERE-----------------------------
//-----------------------------------ISSUE HERE-----------------------------
private void DisplayUSB()
{
richTextBox1.Clear();
var usbDevices = GetUSBDevices();
foreach (var usb in usbDevices)
{
richTextBox1.Text += "USB Device " + usb.DeviceID;
}
}
private void button1_Click(object sender, EventArgs e)
{
switch (button1.Text)
{
case "Start":
button1.Text = "USB";
DisplayProcess();
break;
case "USB":
button1.Text = "Manager";
// DisplayUSB();
break;
case "Manager":
DisplayProcess();
button1.Text = "USB";
break;
}
}
private void button2_Click(object sender, EventArgs e)
{
switch(button1.Text)
{
case "Start":
MessageBox.Show("Please Start The Manager!","REFRESH ERROR");
break;
case "USB":
DisplayProcess();
break;
//case "Manager":
// DisplayUSB();
// break;
}
}
}
}
Errors given are:
Error CS0103 The name 'GetUSBDevices' does not exist in the current context Manager c:\users\*****\documents\visual studio 2017\Projects\Manager\Manager\Form1.cs 38
Error CS1579 foreach statement cannot operate on variables of type '?' because '?' does not contain a public definition for 'GetEnumerator' Manager c:\users*****\documents\visual studio 2017\Projects\Manager\Manager\Form1.cs 40
Code That Does Work (taken from Get List of connected USB Devices and tested personally, works on my PC fine)
namespace ConsoleApplication1
{
using System;
using System.Collections.Generic;
using System.Management;
class Program
{
static void Main(string[] args)
{
var usbDevices = GetUSBDevices();
foreach (var usbDevice in usbDevices)
{
Console.WriteLine("Device ID: {0}, PNP Device ID: {1}, Description: {2}",
usbDevice.DeviceID, usbDevice.PnpDeviceID, usbDevice.Description);
}
Console.Read();
}
}
}
Will very much appreciate any help i can get in the matter, so it will work!
Function GetUSBDevices() is not in System.Management but in the code you copied from the other SO question. So my guess is that you forgot to copy that piece of code ;-).
Related
I have made a console application with which I need to see system information.
When I run the application, I can only see the following on the console:
Usage: sysinfo <cpu|win|net|host|user>
Press any key to continue . . .
I have written this program as console application (.net core), I don't know why I cannot see the information about my system?
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SystemInfo
{
class Program
{
class SysInfo
{
public string win, net, cpu;
public string hostname, username;
public SysInfo()
{
net = Environment.Version.ToString();
win = Environment.OSVersion.ToString();
cpu = Environment.ProcessorCount.ToString();
hostname = Environment.MachineName.ToString();
username = Environment.UserName.ToString();
}
}
static void Main(string[] args)
{
string p;
SysInfo info = new SysInfo();
if (args.Length > 0) p = args[0];
else p = "null";
switch (p)
{
case "cpu":
Console.WriteLine("CPU count: {0}", info.cpu);
break;
case "win":
Console.WriteLine("Windows Version: {0}", info.win);
break;
case "net":
Console.WriteLine(".NET Version: {0}", info.net);
break;
case "host":
Console.WriteLine("Hostname: {0}", info.hostname);
break;
case "user":
Console.WriteLine("Username: {0}", info.username);
break;
default:
Console.WriteLine("Usage: sysinfo <cpu|win|net|host|user>");
break;
}
}
}
}
If you run this in debug (via visual studio) you will need to pass the args.
Go to Project-> Properties. Then click on the Debug tab,
and fill in your arguments in the textbox called Command line
arguments.
refference
If you run the actual compiled exe file, then simply add the desired argument.
For example:
c:\>appname.exe cpu
c:\>appname.exe win
c:\>appname.exe user
....
The console output is the expected behaviour for your application. To get system information, you need to pass a parameter, e.g. like this sysinfo cpu
Edit: If you want to read the strings from the Console you could do it e.g. in a loop
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SystemInfo
{
class Program
{
class SysInfo
{
public string win, net, cpu;
public string hostname, username;
public SysInfo()
{
net = Environment.Version.ToString();
win = Environment.OSVersion.ToString();
cpu = Environment.ProcessorCount.ToString();
hostname = Environment.MachineName.ToString();
username = Environment.UserName.ToString();
}
}
static void Main()
{
string p;
SysInfo info = new SysInfo();
while (true)
{
p = Console.ReadLine();
switch (p)
{
case "cpu":
Console.WriteLine("CPU count: {0}", info.cpu);
break;
case "win":
Console.WriteLine("Windows Version: {0}", info.win);
break;
case "net":
Console.WriteLine(".NET Version: {0}", info.net);
break;
case "host":
Console.WriteLine("Hostname: {0}", info.hostname);
break;
case "user":
Console.WriteLine("Username: {0}", info.username);
break;
default:
Console.WriteLine("Usage: sysinfo <cpu|win|net|host|user>");
break;
}
}
}
}
}
On a sidenote, I'd then also add a case for exiting the loop.
You are reading args when the program starts. Did you forget to pass arguments to your app? Your switch condition is not matched with one of your cases, then it prints out as default case.
You can pass arguments in Visual Studio as answered before: https://stackoverflow.com/a/3697320/3678882
I am fairly new to C#.
I am trying to install a printer programatically using this post I found however I get an exception here:
inputParam.SetPropertyValue("Print", "\\\\http://ip.of.my.server");
An exception of the type "System.Management.ManagementException" has been found in System.Management.dll.
Additional information: Not found.
Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;
namespace Printer
{
class Installation
{
static public string addprinter()
{
ManagementClass win32Printer = new ManagementClass("Win32_Printer");
ManagementBaseObject inputParam = win32Printer.GetMethodParameters("AddPrinterConnection");
inputParam.SetPropertyValue("Print", "\\\\http://ip.of.my.server");
ManagementBaseObject result = (ManagementBaseObject)win32Printer.InvokeMethod("AddPrinterConnection", inputParam, null);
uint errorCode = (uint)result.Properties["returnValue"].Value;
switch (errorCode)
{
case 0:
return ("Successfully connected printer.");
case 5:
return ("Access Denied.");
case 123:
return ("The filename, directory name, or volume label syntax is incorrect.");
case 1801:
return ("Invalid Printer Name.");
case 1930:
return ("Incompatible Printer Driver.");
case 3019:
return("The specified printer driver was not found on the system and needs to be downloaded.");
}
return ("Unkown error.");
}
}
}
And here is the form that calls the code, although I don't think the probleme is there:
private void Send_Click(object sender, EventArgs e)
{
if (true)
{
MessageBox.Show(Installation.addprinter());
}
i am currently deploying matlab over .net i have included my matlab project dll and mwarray.dll of matlab run-time compiler successfully but when i tried in using component data i have 2 errors one is:
name space missing using MathWorks.MATLAB.NET.ComponentData;
second one is:
cannot convert type void MathWorks.MATLAB.NET.Arrays.Mwcellarray in
line cellout = (MWCellArray)obj.braille();
complete code is as mentioned below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CsharpMatlab;
using MathWorks.MATLAB.NET.Arrays;
using MathWorks.MATLAB.NET.Utility;
using MathWorks.MATLAB.NET.ComponentData;
namespace MATCsharp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Code For Matlab to C#");
MWCellArray cellout = null;
CsharpMatlab.CellExampleApp obj = new CsharpMatlab.CellExampleApp();
cellout = (MWCellArray)obj.braille();
MWNumericArray item1 = (MWNumericArray)cellout[1];
MWNumericArray item2 = (MWNumericArray)cellout[2];
MWCharArray item3 = (MWCharArray)cellout[3];
Console.WriteLine("item1 is {0}", item1);
Console.WriteLine("item2 is {0}", item2);
Console.WriteLine("item3 is {0}", item3);
Console.ReadLine();
}emphasized text
}
}
I am a total beginner at C#, but I have used Java a lot. I am trying to use the following code in my app to get location data. I am making a Windows 8 desktop app to use the GPS sensor in my device:
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 Windows.Devices.Sensors;
using Windows.Devices.Geolocation;
using Windows.Devices.Geolocation.Geoposition;
using Windows.Foundation;
namespace Hello_Location
{
public partial class Form1 :
{
public Form1()
{
InitializeComponent();
}
async private void Form1_Load(object sender, EventArgs e)
{
Geolocator loc = new Geolocator();
try
{
loc.DesiredAccuracy = PositionAccuracy.High;
Geoposition pos = await loc.GetGeopositionAsync();
var lat = pos.Coordinate.Latitude;
var lang = pos.Coordinate.Longitude;
Console.WriteLine(lat+ " " +lang);
}
catch (System.UnauthorizedAccessException)
{
// handle error
}
}
private void button1_Click(object sender, EventArgs e)
{
}
}
}
I get this error:
'await' requires that the type
'Windows.Foundation.IAsyncOperation'
have a suitable GetAwaiter method. Are you missing a using directive
for 'System'? C:\Users\clidy\documents\visual studio
2012\Projects\Hello-Location\Hello-Location\Form1.cs
How can I fix this?
Also it will be very useful if you can point me to some resources for C# location and the sensor API for windows desktop apps. Upon googling, I am only getting Windows RT APIs.
To fix your error you have to reference to the link that Bart gave in one of the question's comments.
You might need to add a reference to System.Runtime.WindowsRuntime.dll
as well if you are using mapped types like Windows Runtime event
handlers:
...
That assembly resides in C:\Program Files (x86)\Reference
Assemblies\Microsoft\Framework.NETCore\v4.5
I recently found a "solution" for a similar question: C# desktop application doesn't share my physical location. Maybe you might be interested by my approach: https://stackoverflow.com/a/14645837/674700.
It's more like a workaround and it's not targeting Windows 8, but it works in the end.
alex's solution works!
add that reference and geolocation api starts working like a charm! so do async methods for other sensors!
here is a function i just got working using it.
async public void UseGeoLocation()
{
Geolocator _GeoLocator = new Geolocator();
Geoposition _GeoPosition =
await _GeoLocator.GetGeopositionAsync();
Clipboard.Clear();
Clipboard.SetText("latitude," +
_GeoPosition.Coordinate.Latitude.ToString() +
"," + "longitude," + _GeoPosition.Coordinate.Longitude.ToString() +
"," + "heading," + _GeoPosition.Coordinate.Heading.ToString() +
"," + "speed," + _GeoPosition.Coordinate.Speed.ToString());
Application.Exit();
}
Using DISKPART command line utility, I can get something called a "Location path" which appears to give me what I need, you can view this by using the command detail disk after selecting one of your disks in diskpart.
It appears I can get this information programatically via this class: MSFT_Disk
I am unsure about how to get an instance of this class. I have a few examples of using a ManagementObjectSearcher for WMI classes but that method is not working for me, I am also unsure of MSFT_Disk's availability in Windows 7 as the page mentions that this is for Windows 8.
Does anyone know of a good way to get SATA channel information or the "location path" of a disk?
If you want to not require Windows 8, I believe WMI is the way to go:
using System;
using System.Linq;
using System.Management;
namespace DiskScanPOC
{
class Program
{
static void Main()
{
var managementScope = new ManagementScope();
//get disk drives
var query = new ObjectQuery("select * from Win32_DiskDrive");
var searcher = new ManagementObjectSearcher(managementScope, query);
var oReturnCollection = searcher.Get();
//List all properties available, in case the below isn't what you want.
var colList = oReturnCollection.Cast<ManagementObject>().First();
foreach (var property in colList.Properties)
{
Console.WriteLine("Property: {0} = {1}", property.Name, property.Value);
}
//loop through found drives and write out info
foreach (ManagementObject oReturn in oReturnCollection)
{
Console.WriteLine("Name : " + oReturn["Name"]);
Console.WriteLine("Target Id: " + oReturn["SCSITargetId"]);
Console.WriteLine("Port: " + oReturn["SCSIPort"]);
}
Console.Read();
}
}
}
I didn't crack open my case to verify the SATA port numbers, but the above app looks like it gives reasonable results on my machine with 3 SATA hard drives.
If you want to get the location path, SetupDiGetDeviceRegistryProperty is the function you're looking for. Set the property value to SPDRP_LOCATION_INFORMATION.
I'm assuming you already know how to enumerate devices to get the DeviceInfoSet and DeviceInfoData.
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;
namespace Hard_Disk_Interface
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCheck_Click(object sender, EventArgs e)
{
WqlObjectQuery q = new WqlObjectQuery("SELECT * FROM Win32_IDEController");
ManagementObjectSearcher res = new ManagementObjectSearcher(q);
lblHDDChanels.Text = string.Empty;
foreach (ManagementObject o in res.Get())
{
string Caption = o["Caption"].ToString();
lblHDDChanels.Text += Caption + "\n\n";
if (Caption.Contains("Serial"))
{
lblInterface.Text = "S-ATA";
}
}
}
}
}
Note: First Add the reference of System.Management.dll of .net freamwork 4.0