Most queries you'll find on the internet don't do it, but in the general case, you must escape raw strings you pass to WQL queries (in your case objectId
contains special characters), using the backslash character, with a method like this:
public static string EscapeWql(string text)
{
if (text == null)
return null;
var sb = new StringBuilder(text.Length);
foreach (var c in text)
{
if (c == '\' || c == ''' || c == '"')
{
sb.Append('\');
}
sb.Append(c);
}
return sb.ToString();
}
So your method should now look like this:
public static void GetPartitionInfo(object objectId)
{
var scope = new ManagementScope(@"rootMicrosoftWindowsStorage");
var query = new ObjectQuery("ASSOCIATORS OF {MSFT_Disk.ObjectId="" + EscapeWql((string)objectId) + ""} WHERE AssocClass = MSFT_DiskToPartition");
using (var searcher = new ManagementObjectSearcher(scope, query))
{
using (var queryCollection = searcher.Get())
{
foreach (var partition in queryCollection)
{
Console.WriteLine(partition["Guid"]);
}
}
}
}
PS: don't forget using statements on IDisposable
classes.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…