使用WMI来控制Windows目录 和windows共享机制

1.使用WMI来控制Windows目录

本文主要介绍如何使用WMI来查询目录是否存在、文件是否存在、如何建立目录、删除目录,删除文件、如何利用命令行拷贝文件,如何利用WMI拷贝文件

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

namespace TJVictor.WMI
{
    public class Win32_Directory : WMIBaseClass
    {
        #region Property
        private int timeout = 30;
        public int TimeOut
        {
            get { return timeout; }
            set { timeout = value; }
        }
        #endregion

        #region Construction
        public Win32_Directory()
            : base()
        {
            base.Connection();
        }
        public Win32_Directory(string domain, string Ip, string user, string psw)
            : base(domain, Ip, user, psw)
        {
            base.Connection();
        }
        #endregion

        #region public function
        public bool IsDirExist(string path)
        {
            string wqlSelect = "select * FROM Win32_Directory where Name='{0}'";
            if (!GetSelectQueryCollection(wqlSelect, path.Replace("//", "////")).Count.Equals(0))
                return true;
            return false;
        }

        public bool IsFileExist(string path)
        {
            string wqlSelect = "select * FROM CIM_DataFile where Name='{0}'";
            if (!GetSelectQueryCollection(wqlSelect, path.Replace("//", "////")).Count.Equals(0))
                return true;
            return false;
        }

        public void CreateDir(string path)
        {
            if (IsDirExist(path))
            {
                throw new TJVictor.WMI.WmiException.DirectoryException(string.Format("无法创建 {0}, 目录已经存在",path));
            }
            ManagementClass processClass = new ManagementClass("Win32_Process");
            processClass.Scope = base.Scope;
            object[] methodArgs = { string.Format("cmd.exe /c md {0}", path), null, null, 0 };
            // Method Options
            object result = processClass.InvokeMethod("Create", methodArgs);
            CheckExceptionClass.CheckDirectoryExcepton(int.Parse(result.ToString()));
        }

        public void DeleteDir(string path)
        {
            if (!IsDirExist(path))
                throw new TJVictor.WMI.WmiException.DirectoryException(string.Format("无法删除 {0}, 目录不存在",path));
            string wqlSelect = "select * FROM Win32_Directory where Name='{0}'";
            object result = 0;
            foreach (ManagementObject mo in GetSelectQueryCollection(wqlSelect, path.Replace("//", "////")))
            {
                result = mo.InvokeMethod("Delete", null);
                break;
            }
            CheckExceptionClass.CheckDirectoryExcepton(int.Parse(result.ToString()));
        }

        public void DeleteFile(string flieName)
        {
            if (!IsFileExist(flieName))
                throw new TJVictor.WMI.WmiException.DirectoryException(string.Format("{0} 文件不存在",flieName));
            string wqlSelect = "select * FROM CIM_DataFile where Name='{0}'";
            object result = 0;
            foreach (ManagementObject mo in GetSelectQueryCollection(wqlSelect, flieName.Replace("//", "////")))
            {
                result = mo.InvokeMethod("Delete", null);
                break;
            }
            CheckExceptionClass.CheckDirectoryExcepton(int.Parse(result.ToString()));
        }

        public void CopyDirByProcess(string oldDirPath, string newDirPath)
        {
            int tempTimeOut = this.timeout;
            Process copyProcess = new Process();
            copyProcess.StartInfo.CreateNoWindow = true;
            copyProcess.StartInfo.UseShellExecute = false;
            copyProcess.StartInfo.FileName = string.Format(@"C:/WINDOWS/system32/xcopy.exe");
            copyProcess.StartInfo.Arguments = string.Format(@"/e /y {0} {1}", oldDirPath, newDirPath);
            copyProcess.Start();
            while (!copyProcess.HasExited)
            {
                Thread.Sleep(1000);
                copyProcess.Refresh();
                if (tempTimeOut.Equals(0))
                    throw new WmiException.DirectoryException(string.Format("从 {0} 到 {1} 复制文件失败--{2}秒超时", oldDirPath, newDirPath, this.timeout));
                tempTimeOut--;
            }
        }

        public void CopyDirByWmi(string oldDirPath, string newDirPath)
        {
            int tempTimeOut = this.timeout;
            ManagementClass processClass = new ManagementClass("Win32_Process");
            processClass.Scope = base.Scope;

            ManagementBaseObject mbo = processClass.GetMethodParameters("Create");
            mbo["CommandLine"] = string.Format("xcopy.exe /e /y {0} {1}", oldDirPath, newDirPath + "//*.*");
            ManagementBaseObject ob = processClass.InvokeMethod("Create", mbo, null);

            string wqlSelect = "select * FROM Win32_Process where ProcessID='{0}'";
            while (!GetSelectQueryCollection(wqlSelect, ob["ProcessID"].ToString()).Count.Equals(0))
            {
                if (tempTimeOut.Equals(0))
                {
                    throw new WmiException.DirectoryException(string.Format("从 {0} 到 {1} 拷贝文件失败----超时", oldDirPath, newDirPath));
                }
                tempTimeOut--;
                Thread.Sleep(1000);
            }
        }
        #endregion
    }
}

2.使用WMI来操作Windows共享机制

本文主要介绍如何使用WMI来查看共享目录是否存在、如何建立信认、如何断开信认、如何远程建立共享目录,删除共享目录

代码如下:

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

namespace TJVictor.WMI
{
    public class Win32_Share:WMIBaseClass
    {
        #region Property
        private int timeout = 30;
        public int TimeOut
        {
            get { return timeout; }
            set { timeout = value; }
        }

        string wqlSelect = string.Empty;
        #endregion

        #region Construction
        public Win32_Share()
            : base()
        {
            wqlSelect = "select * FROM Win32_Share where Name='{0}'";
            base.Connection();
        }
        public Win32_Share(string domain, string Ip, string user, string psd)
            : base(domain, Ip, user, psd)
        {
            wqlSelect = "select * FROM Win32_Share where Name='{0}'";
            base.Connection();
        }
        #endregion

        #region public function
        public bool IsShareDirectoryExist(string shareName)
        {
            if (!GetSelectQueryCollection(wqlSelect, shareName).Count.Equals(0))
                return true;
            else
                return false;
        }

        public void ConnectionCredit()
        {
            string creditUser = base.User;
            //判断是否为域用户
            if (!base.Domain.Equals(string.Empty))
                creditUser = base.Domain + "//" + base.User;

            Process connectionCreditProcess = new Process();
            connectionCreditProcess.StartInfo.CreateNoWindow = true;
            connectionCreditProcess.StartInfo.UseShellExecute = false;
            connectionCreditProcess.StartInfo.FileName = string.Format(@"C:/WINDOWS/system32/cmd.exe");
            connectionCreditProcess.StartInfo.Arguments = string.Format("/c net use ////{0} /"{1}/" /user:/"{2}/"", base.Ip
                , base.Password, creditUser);
            connectionCreditProcess.Start();

            int tempTimeout = this.timeout;
            while (!connectionCreditProcess.HasExited)
            {
                Thread.Sleep(500);
                connectionCreditProcess.Refresh();
                if(tempTimeout.Equals(0))
                    throw new TJVictor.WMI.WmiException.ShareException(
                        string.Format("与{0}建立信任关系失败,建立超时",base.Ip));
                tempTimeout--;
            }
        }

        public void DisconnectionCredit()
        {
            Process disconnectionCreditProcess = new Process();
            disconnectionCreditProcess.StartInfo.CreateNoWindow = true;
            disconnectionCreditProcess.StartInfo.UseShellExecute = false;
            disconnectionCreditProcess.StartInfo.FileName = string.Format(@"C:/WINDOWS/system32/cmd.exe");
            disconnectionCreditProcess.StartInfo.Arguments = string.Format(@"/c net use //{0}/ipc$ /delete", base.Ip);
            disconnectionCreditProcess.Start();

            int tempTimeout = this.timeout;
            while (!disconnectionCreditProcess.HasExited)
            {
                Thread.Sleep(500);
                disconnectionCreditProcess.Refresh();
                if(tempTimeout.Equals(0))
                    throw new TJVictor.WMI.WmiException.ShareException(
                        string.Format("与{0}断开信任关系失败,断开超时", base.Ip));
                tempTimeout--;
            }
        }

        public void CreateShareDir(string name, string shareDir)
        {
            Win32_Directory directory = new Win32_Directory(base.Domain, base.Ip, base.User, base.Password);
            if(!directory.IsDirExist(name))
                throw new TJVictor.WMI.WmiException.ShareException(
                    string.Format("无法在{0}上建立{1}目录共享,目录不存在", base.Ip,shareDir));

            ManagementClass processClass = new ManagementClass("Win32_Share");
            processClass.Scope = base.Scope;

            string method = "Create";
            ManagementBaseObject inputArgs = processClass.GetMethodParameters(method);
            inputArgs["Name"] = name;
            inputArgs["Path"] = shareDir;
            inputArgs["Description"] = "wmi Create shared";
            inputArgs["Type"] = 0; // Disk share type
            ManagementBaseObject result = processClass.InvokeMethod(method, inputArgs, null);
            CheckExceptionClass.CheckShareException(int.Parse(result["ReturnValue"].ToString()));

            //检测是否已经建立共享
            int tempTimeout = this.timeout;
            while (!IsShareDirectoryExist(name))
            {
                processClass.InvokeMethod(method, inputArgs, null);//再建立一次
                if(tempTimeout.Equals(0))
                    throw new TJVictor.WMI.WmiException.ShareException(
                        string.Format("无法在{0}上建立{1}目录共享,建立超时", base.Ip, name));
                tempTimeout--;
            }
        }

        public void DeleteShareDir(string name)
        {
            object result = 0;
            foreach (ManagementObject mo in GetSelectQueryCollection(wqlSelect,name))
            {
                result = mo.InvokeMethod("Delete", null);
                break;
            }
            CheckExceptionClass.CheckShareException(int.Parse(result.ToString()));

            //检测是否已经删除共享
            int tempTimeout = this.timeout;
            while (IsShareDirectoryExist(name))
            {
                foreach (ManagementObject mo in GetSelectQueryCollection(wqlSelect, name))//再删除一次
                {
                    result = mo.InvokeMethod("Delete", null);
                    break;
                }
                if(tempTimeout.Equals(0))
                    throw new TJVictor.WMI.WmiException.ShareException(
                         string.Format("无法在{0}上删除{1}共享,建立超时", base.Ip, name));
                tempTimeout--;
            }
        }
        #endregion
    }
}
原文地址:https://www.cnblogs.com/tianma3798/p/3560619.html