2

我正在尝试获取 c:\windows\ntds\ 目录中存在的这个 dsa 文件的大小。

我在这里遇到错误,我不知道为什么。错误是“无效查询”。

当我使用不同的 WMI 类时,我似乎经常遇到这个错误。

我不知道为什么会出现这个错误以及如何解决这个问题?

下面的代码中是否有任何错误,如何解决?

为什么我们会得到这个 Invalid Query 错误,它的来源是什么?它的内部异常将始终为空?

private int getDatabaseFileSize(string DSADatabaseFile, string machineName)
        {
            string scope = @"\\" + machineName + @"\root\CIMV2";
            string query = string.Format("Select FileSize from CIM_DataFile WHERE Name = '{0}'", DSADatabaseFile);
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
            ManagementObjectCollection collection = searcher.Get();
            foreach (ManagementObject mobj in searcher.Get())
            {
                Console.WriteLine("File Size : " + mobj["FileSize"]);
            }
            return 0;
        }

谢谢

4

1 回答 1

3

我猜,但由于您的查询在语法上是正确的并且使用了正确的字段和对象名称,我认为这是因为您将字符串 "C:\Windows\NTDS\ntds.dit" 传递为DSADatabaseFile. 这对于 C# 中的“典型”使用是正确的,比如在使用Path类时,等等,但不是在这里。

您需要将带有两个反斜杠的文件名传递给 WMI。但是,由于 C# 已经要求,您需要有效地通过四个:

 getDatabaseFileSize("C:\\\\Windows\\\\NTDS\\\\ntds.dit", machine)

或使用逐字字符串文字:

 getDatabaseFileSize(@"C:\\Windows\\NTDS\\ntds.dit", machine);

更新这里是一个完整的例子:

// Compile with: csc foo.cs /r:System.Management.dll

using System;
using System.Management;

namespace Foo
{
    public class Program
    {
        private int getDatabaseFileSize(string DSADatabaseFile, string machineName)
        {
            string scope = @"\\" + machineName + @"\root\CIMV2";
            string query = string.Format("Select FileSize from CIM_DataFile WHERE Name = '{0}'", DSADatabaseFile);
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
            ManagementObjectCollection collection = searcher.Get();
            foreach (ManagementObject mobj in searcher.Get())
            {
                Console.WriteLine("File Size : " + mobj["FileSize"]);
            }
            return 0;
        }

        public static void Main(string[] args)
        {
            var p = new Program();

            // These work
            p.getDatabaseFileSize("C:/boot.ini", ".");
            p.getDatabaseFileSize(@"C:\\boot.ini", ".");
            p.getDatabaseFileSize("C:\\\\boot.ini", ".");

            // These fail
            try {
                p.getDatabaseFileSize("C:\\boot.ini", ".");
            } catch (ManagementException ex) { 
                Console.WriteLine("Failed: {0}", ex.ErrorCode);
            }
            try {
                p.getDatabaseFileSize(@"C:\boot.ini", ".");
            } catch (ManagementException ex) { 
                Console.WriteLine("Failed: {0}", ex.ErrorCode);
            }
        }
    }
}

编译:

(预期的)输出是:

File Size : 313
File Size : 313
Failed: InvalidQuery.
Failed: InvalidQuery.

更新似乎已经有一个相关的问题(提到需要\\\\代替\\)。

于 2012-05-02T05:51:31.037 回答