2

如何通过 WMI 和 C# 查询远程计算机中的文件夹大小。我需要通过 WMI 在远程系统的 C:\Users 中找到每个用户的文件夹大小。

我尝试了 Win32_Directory , CMI_DataFile 但无法找到所需的答案。请帮忙!!

4

1 回答 1

3

要使用 WMI 获取文件夹的大小,您必须使用类遍历文件CIM_DataFile,然后从FileSize属性中获取每个文件的大小。

试试这个示例(这个代码不是递归的,我把这个任务留给你)。

using System; 
using System.Collections.Generic;
using System.Management;
using System.Text;

namespace GetWMI_Info
{
    class Program
    {
// Directory is a type of file that logically groups data files 'contained' in it, 
// and provides path information for the grouped files.

        static void Main(string[] args)
        {
            try
            {
                string ComputerName = "localhost";
                ManagementScope Scope;                

                if (!ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase)) 
                {
                    ConnectionOptions Conn = new ConnectionOptions();
                    Conn.Username  = "";
                    Conn.Password  = "";
                    Conn.Authority = "ntlmdomain:DOMAIN";
                    Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), Conn);
                }
                else
                    Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);

                Scope.Connect();

                string Drive= "c:";
                //look how the \ char is escaped. 
                string Path="\\\\FolderName\\\\";
                UInt64 FolderSize = 0;

                ObjectQuery Query = new ObjectQuery(string.Format("SELECT * FROM CIM_DataFile Where Drive='{0}' AND Path='{1}' ", Drive, Path));
                ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);

                foreach (ManagementObject WmiObject in Searcher.Get())
                {
                    Console.WriteLine("{0}", (string)WmiObject["FileName"]);// String
                    FolderSize +=(UInt64)WmiObject["FileSize"];
                }

                Console.WriteLine("{0,-35} {1,-40}", "Folder Size", FolderSize.ToString("N"));

            }
            catch (Exception e)
            {
                Console.WriteLine(String.Format("Exception {0} Trace {1}",e.Message,e.StackTrace));
            }
            Console.WriteLine("Press Enter to exit");
            Console.Read();
        }
    }

}
于 2012-10-18T01:50:47.417 回答