Invalid Query C# - c#

today i wrote my second Code in C#
why wont it work? the code ist (as it seems) correct!
error code: InvalidQuery
Code:
static void Main(string[] args)
{
GetComponent("Win32_Processor", "Name");
Console.Read();
Console.ReadKey();
}
private static void GetComponent(string hwclass, string syntax)
{
ManagementObjectSearcher mos = new ManagementObjectSearcher ("root\\CIMV2","SELECT * FROM" + hwclass);
foreach(ManagementObject mj in mos.Get())
{
Console.WriteLine(Convert.ToString(mj[syntax]));
}
}

Please, use formatting or string interpolation (C# 6.0+) to avoid syntax errors:
private static void GetComponent(string hwclass, string syntax) {
//DONE: keep query readable
string query =
$#"select *
from {hwclass}"; // <- you've missed space here
//DONE: wrap IDisposable into using
using (ManagementObjectSearcher mos = new ManagementObjectSearcher("root\\CIMV2", query)) {
foreach(ManagementObject mj in mos.Get())
Console.WriteLine(Convert.ToString(mj[syntax]));
}
}

You are missing a space after the "FROM":
("root\\CIMV2","SELECT * FROM" + hwclass);
Change to:
("root\\CIMV2","SELECT * FROM " + hwclass);

Related

how to format drive with 32KB cluster

I am not a C# programer but I need to format drive with 32KB cluster using C#. I found "Format method of the Win32_Volume class" but when I am trying to format drive I always get an error 15 (Cluster size is too small). This is my code:
public static int DriveFormatting(string driveLetter)
{
string FileSystem = "FAT32", Label = "";
Boolean QuickFormat = true, EnableCompression = false;
UInt32 ClusterSize = 32;
int result = -1;
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Volume WHERE DriveLetter = '"+ driveLetter +"'");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach(ManagementObject management in searcher.Get())
{
Console.WriteLine("Formating disk " + driveLetter + "...");
result = Convert.ToInt32(management.InvokeMethod("Format", new object[] { FileSystem, QuickFormat, ClusterSize, Label, EnableCompression }));
}
return result;
}
How can I do this? Thanks in advance.

C# console how to hold output simplest version?

I'm very new to C# ; does someone know how to write ALL output lines to a .txt file without starting new process?
This code writes only the last record:
class Program
{
static void Main(string[] args)
{
WezKomponent("Win32_DiskDrive", "Model");
Console.ReadKey();
}
private static void WezKomponent(string ass, string sax)
{
ManagementObjectSearcher wez = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM " + ass);
foreach (ManagementObject pie in wez.Get())
{
Console.WriteLine(Convert.ToString(pie[sax]));
StreamWriter SW = new StreamWriter(#"HDD.txt");
SW.WriteLine(Convert.ToString(pie[sax]));
SW.Close();
}
}
}
Actually, it does indeed write all the records to the file, the problem is that you overwrite the file each time, and thus what you observe is that only the last record is kept.
There are two solutions to this:
Open the file before the loop, write all the records, then close the file
Open the file inside the loop, but do so in a manner that will append new content
In general it's easier to get the first one right, so here's how to do it that way:
Move the opening of the stream up and out of the loop
Move the closing of the stream down and out of the loop
In essence you take these lines of code:
private static void WezKomponent(string ass, string sax)
{
ManagementObjectSearcher wez = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM " + ass);
foreach (ManagementObject pie in wez.Get())
{
Console.WriteLine(Convert.ToString(pie[sax]));
StreamWriter SW = new StreamWriter(#"HDD.txt");
SW.WriteLine(Convert.ToString(pie[sax]));
SW.Close();
}
}
And change them to this:
private static void WezKomponent(string ass, string sax)
{
ManagementObjectSearcher wez = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM " + ass);
StreamWriter SW = new StreamWriter(#"HDD.txt");
foreach (ManagementObject pie in wez.Get())
{
Console.WriteLine(Convert.ToString(pie[sax]));
SW.WriteLine(Convert.ToString(pie[sax]));
}
SW.Close();
}
Additionally, to be more failsafe in case of errors, it is better using this syntax:
using (... = new SomethingThatImplementsIDisposable(...))
{
}
than this:
... = new SomethingThatImplementsIDisposable(...);
...
...Close(); // or .Dispose();
So here's a better version of your method:
private static void WezKomponent(string ass, string sax)
{
using (ManagementObjectSearcher wez = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM " + ass))
using (StreamWriter SW = new StreamWriter(#"HDD.txt"))
{
foreach (ManagementObject pie in wez.Get())
{
Console.WriteLine(Convert.ToString(pie[sax]));
SW.WriteLine(Convert.ToString(pie[sax]));
}
}
}
The reason why this is better is because of the chance of exceptions in your code. If that happens, SW.Close(); will not be executed which means that you leave the stream and the file open, at least longer than intended. With a using clause like this, if an exception happens inside, the Dispose method on these objects will be called, closing the file, and in this case the ManagementObjectSearcher object as well.
So is there any way to improve your code even further? Yes, but only if you either know this other syntax I'm about to show, or willing to learn. Since you said you were new to C# you might not know it, and you might want to get comfortable with your existing code before making it even more complex from your point of view.
There's several ways to write to text files, StreamWriter is one of them, File.WriteAllLines is another but this expects the content to write to be provided as a collection of strings that will be written as a series of lines to the file.
So how can we get from your ManagementObjectSearcher object to a list of strings?
Through a set of syntax and .NET classes collectively known as "LINQ" or "Language INtegrated Query".
Here's a shorter version of your method:
private static void WezKomponent(string ass, string sax)
{
using (ManagementObjectSearcher wez = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM " + ass))
{
File.WriteAllLines(#"HDD.txt", wez
.Get()
.Select(pie => ConvertToString(pie[sax])));
}
}
This can even be shortened down to just put more on each line and removing some unnecessary braces, and using var when the exact type can easily be discerned from the surrounding code:
private static void WezKomponent(string ass, string sax)
{
using (var wez = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM " + ass))
File.WriteAllLines(#"HDD.txt", wez.Get().Select(pie => ConvertToString(pie[sax])));
}
class Program
{
static void Main(string[] args)
{
WezKomponent("Win32_DiskDrive", "Model");
Console.ReadKey();
}
private static void WezKomponent(string ass, string sax)
{
ManagementObjectSearcher wez = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM " + ass);
StreamWriter SW = new StreamWriter(#"HDD.txt");
foreach (ManagementObject pie in wez.Get())
{
Console.WriteLine(Convert.ToString(pie[sax]));
SW.WriteLine(Convert.ToString(pie[sax]));
}
SW.Close();
}
Try initializing StreamWriter in a different manner.
StreamWriter SW = new StreamWriter(#"HDD.txt", append: true);
Note append: true in the constructor call.

I get an invalid query error when foreach (ManagementObject mo in mos.Get())

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Management;
namespace NetPrimate_Provisioning_Tool_1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnGet_Click(object sender, EventArgs e)
{
foreach (string cpu in GetComponents("WIN32_Processor", "Name"))
{
txtInfo.AppendText("CPU:" + cpu + Environment.NewLine);
}
foreach (string gpu in GetComponents("WIN32_VideoController", "Name"))
{
txtInfo.AppendText("GPU:" + gpu + Environment.NewLine);
}
foreach (string os in GetComponents("WIN32_OperatingSystem", "Caption"))
{
txtInfo.AppendText("OS:" + os);
if(Environment.Is64BitOperatingSystem)
{
txtInfo.AppendText("64Bit" + Environment.NewLine);
}
else
{
txtInfo.AppendText("32Bit" + Environment.NewLine);
}
}
string ram = GetComponents("WIN32_ComputerSystem", "TotalPhysicalMemory")[0];
double db_ram = Convert.ToDouble(ram) / 1073741824;
int size = (int)Math.Ceiling(db_ram);
txtInfo.AppendText("RAM:" + size.ToString() + "GB");
}
public List<string> GetComponents(string hwclass, string syntax)
{
List<string> details = new List<string>();
ManagementObjectSearcher mos = new ManagementObjectSearcher("root\\CIMV2", "SELECT*FROM " + hwclass);
foreach (ManagementObject mo in mos.Get()) ##ERROR HERE##
{
details.Add(mo[syntax].ToString());
}
return details;
}
}
}
Hi All im getting invalid query on the line i have marked (##ERROR HERE##) but i cant seem to locate a fix can anyone help. This script should look at the system and get system information.
Photo of the Program
Your query is incorrect, you need to insert whitespace between tokens: "SELECT * FROM " + hwclass, then it will work.

Lenovo BIOS WMI - InvalidQuery

I'm about to create a tool which gets some system information.
Only the Lenovo BIOS (WakeOnLAN) request isn't doing what I want.
The debugger always stops with a "invalid request" error message.
I tried the following...
ManagementObjectSearcher searcher = new ManagementObjectSearcher("\\\\" + textBox1.Text + "\\root\\wmi", "SELECT * FROM Lenovo_BiosSetting WHERE InstanceName='ACPI\\PNP0C14\\1_0'");
ManagementObjectSearcher searcher = new ManagementObjectSearcher("\\\\" + textBox1.Text + "\\root\\wmi:Lenovo_BiosSetting.InstanceName='ACPI\\PNP0C14\\1_0'");
Code:
//LenovoWOL
public string GetLenovoWOL()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("\\\\" + textBox1.Text + "\\root\\wmi:Lenovo_BiosSetting", "SELECT * FROM ACPI\\PNP0C14\\1_0");
foreach (ManagementObject wmi in searcher.Get())
{
try
{
return Environment.NewLine + wmi.GetPropertyValue("CurrentSetting").ToString();
}
catch { }
}
return "Unknown";
}
Only if I remove the InstanceName part, the code works.
Could someone if you tell me, what I'm doing wrong.
Thanks for your help
Adrian
I found a solution.
Here my code. It's not pretty but it works.
ManagementPath path = new ManagementPath()
{
NamespacePath = #"root\wmi",
Server = textBox1.Text
};
ManagementScope scope = new ManagementScope(path);
SelectQuery Sq = new SelectQuery("Lenovo_BiosSetting");
ManagementObjectSearcher objOSDetails = new ManagementObjectSearcher(scope, Sq);
ManagementObjectCollection osDetailsCollection = objOSDetails.Get();
foreach (ManagementObject MO in osDetailsCollection)
{
if (MO["CurrentSetting"].ToString().Contains("WakeOnLAN"))
{
string[] arr = new string[3];
ListViewItem itm;
//add items to ListView
arr[0] = "";
arr[1] = "WakeOnLAN";
arr[2] = MO["CurrentSetting"].ToString();
itm = new ListViewItem(arr);
listView200.Items.Add(itm);
}
}
Adrian

How to search for a file on a remote system by file name using WMI in C#?

How do I search for a file on a remote system by it's filename using WMI and C#?
Try this code and check this.
Download also WMI Code Creator ( check on google because I can't link it due to my reputation <10) to easily test your WMI query.
using System;
using System.Management;
namespace WMISample
{
public class MyWMIQuery
{
public static void Main()
{
try
{
ConnectionOptions oConn = new ConnectionOptions();
oConn.Impersonation = ImpersonationLevel.Impersonate;
oConn.EnablePrivileges = true;
string[] arrComputers = "clientName"};
foreach (string strComputer in arrComputers)
{
Console.WriteLine("==========================================");
Console.WriteLine("Computer: " + strComputer);
Console.WriteLine("==========================================");
ManagementObjectSearcher searcher = new ManagementObjectSearcher
(
new ManagementScope("\\\\" + strComputer + "\\root\\CIMV2", oConn),
new ObjectQuery( #"SELECT * FROM CIM_DataFile WHERE Name = 'WhatyouWant.ToSearch'")
);
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("CIM_DataFile instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("Path: {0}", queryObj["Path"]);
}
}
}
catch(ManagementException err)
{
MessageBox.Show("An error occurred while querying for WMI data: " + err.Message);
}
}
}
}

Categories