使用WMI来操作Windows共享机制

本文介绍通过Windows Management Instrumentation (WMI) 来管理共享目录的方法,包括检查共享目录是否存在、建立及断开信任连接、远程创建和删除共享目录。

本文主要介绍如何使用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
    }
}
<style type="text/css"> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }</style>

如需转载,请注明本文原创自优快云 TJVictor专栏:http://blog.youkuaiyun.com/tjvictor

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值