How to query Folder Size in remote computer through WMI and C#

穿精又带淫゛_ 提交于 2019-12-24 04:15:08

问题


How to query Folder Size in remote computer through WMI and C#. I need to find the each User's folder size in C:\Users in remote System through WMI.

I tried Win32_Directory , CMI_DataFile but not able to find the desired answer. Please help!!


回答1:


To get the size of a folder using the WMI, you must iterate over the files using the CIM_DataFile class and then get the size of each file from the FileSize property.

Try this sample (this code is not recursive, I leave such task for you).

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();
        }
    }

}


来源:https://stackoverflow.com/questions/12945121/how-to-query-folder-size-in-remote-computer-through-wmi-and-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!