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 = ;
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())
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())
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, };
// 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 = ;
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 = ;
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();
copyProcess.Refresh();
if (tempTimeOut.Equals())
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())
{
if (tempTimeOut.Equals())
{
throw new WmiException.DirectoryException(string.Format("从 {0} 到 {1} 拷贝文件失败----超时", oldDirPath, newDirPath));
}
tempTimeOut--;
Thread.Sleep();
}
}
#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 = ;
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())
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} /"{}/" /user:/"{}/"", base.Ip
, base.Password, creditUser);
connectionCreditProcess.Start(); int tempTimeout = this.timeout;
while (!connectionCreditProcess.HasExited)
{
Thread.Sleep();
connectionCreditProcess.Refresh();
if(tempTimeout.Equals())
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();
disconnectionCreditProcess.Refresh();
if(tempTimeout.Equals())
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"] = ; // 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())
throw new TJVictor.WMI.WmiException.ShareException(
string.Format("无法在{0}上建立{1}目录共享,建立超时", base.Ip, name));
tempTimeout--;
}
} public void DeleteShareDir(string name)
{
object result = ;
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())
throw new TJVictor.WMI.WmiException.ShareException(
string.Format("无法在{0}上删除{1}共享,建立超时", base.Ip, name));
tempTimeout--;
}
}
#endregion
}
}

使用WMI来控制Windows目录 和windows共享机制的更多相关文章

  1. linux目录和Windows目录对比

    linux目录和Windows目录对比 我们应该知道 Windows 有一个默认的安装目录专门用来安装软件.Linux 的软件安装目录也应该是有讲究的,遵循这一点,对后期的管理和维护也是有帮助的. / ...

  2. 控制Arduino的利器-Windows Remote Arduino

    1. 概述 相信很多朋友已经在玩 Arduino了,而且一般都是使用官方的Arduino IDE来写程序控制Arduino硬件.为了能够实现更加方便的控制,微软在Windows IoT计划中推出了Wi ...

  3. [转] 控制Arduino的利器-Windows Remote Arduino

    原文地址:控制Arduino的利器-Windows Remote Arduino 1. 概述 相信很多朋友已经在玩 Arduino了,而且一般都是使用官方的Arduino IDE来写程序控制Ardui ...

  4. QT正则表达式学习(Windows目录禁止九个字符)

    exp 正则表达式30分钟入门教程 http://deerchao.net/tutorials/regex/regex.htm 元字符 .*^\d\b\s,当然还有\,还有中括号[] .是一个元字符, ...

  5. [Windows Phone] 在 Windows Phone 8 控制闪光灯

    原文:[Windows Phone] 在 Windows Phone 8 控制闪光灯 ? 前言 在 Windows Phone 如果想要控制闪光灯,该怎麽做?在 Windows Phone 8 提供类 ...

  6. Windows服务器如何查看共享目录信息

    查看Windows服务器上的共享目录的相关信息,可以使用两种方式: 1:命令net share 查看: 2:通过计算机管理的Shared Folders查看

  7. Delphi调用API函数获取Windows目录信息、获取System目录信息、获取Temp临时文件目录信息

    var Str1, Str2: Array[..Max_Path]of Char;//开辟缓冲区 Str3: Array[..]of Char; begin GetWindowsDirectory(@ ...

  8. Linux 挂载windows目录

    1.默认情况下,Linux服务器会装有samba-client,但是没有装samba-server.但是访问Windows系统共享,安装有samba-client就可以了. [root@test ~] ...

  9. 将windows目录共享到linux

    1.将windows目录共享 2.安装cifs 3.  mount -t cifs -o username=电脑登陆用户名,password=电脑登陆用户密码 //127.0.0.1/abc /var ...

随机推荐

  1. 简述MVC思想 与PHP如何实现MVC

    我相信已经有很多这样的文章了,但是我今天还是愿意把自己的经验与大家分享一下.纯属原创,我也没什么保留,希望对新手有帮助,有说的不对的地方,也欢迎指出. 什么是MVC? 简单的说就是将网站源码分类.分层 ...

  2. javascript summary

    Client Javascript HTML5: http://www.html5rocks.com/en/ Libraray: JQuery, JQuery Mobile, Zepto, MoolT ...

  3. c#语句 (随堂练习)

    1. 方程ax²+bx+c=0:一元二次方程.求根    输入a,b,c的值    Δ=b²-4ac:若Δ<0方程无实根    若Δ>0,方程有两个不相同的实根x1 x2gen    若Δ ...

  4. c++ explicit

    C++ explicit关键字用来修饰类的构造函数,表明该构造函数是显式的,既然有"显式"那么必然就有"隐式",那么什么是显示而什么又是隐式的呢? 如果c++类 ...

  5. java学习面向对象之继承

    在我们编写程序的过程当中,会遇到这种情况: 比如现在有一个狗,他的功能有跑,有跳,有吃,有叫,属性有雌雄,大小,颜色等等,同时现在我们也有一个猫,上述功能她也有.这个时候我们写代码的时候,就得分别把上 ...

  6. super返回不过来

    class Fruit {     String color = "未确定颜色";     //定义一个方法,该方法返回调用该方法的实例     public Fruit getT ...

  7. soap协议

    定义: 简单对象访问协议是交换数据的一种协议规范,是一种轻量的.简单的.基于XML(标准通用标记语言下的一个子集)的协议,它被设计成在WEB上交换结构化的和固化的信息. 协议中的几个关键词术语: SO ...

  8. 【搜索】【并查集】Codeforces 691D Swaps in Permutation

    题目链接: http://codeforces.com/problemset/problem/691/D 题目大意: 给一个1到N的排列,M个操作(1<=N,M<=106),每个操作可以交 ...

  9. HDOJ 2027 统计元音

    Problem Description 统计每个元音字母在字符串中出现的次数. Input 输入数据首先包括一个整数n,表示测试实例的个数,然后是n行长度不超过100的字符串. Output 对于每个 ...

  10. SVN强制注释

    1.目的 在使用SVN作为版本控制的时候,强制提交的人员写注释,这样能确保每次提交都有注释,方便查看 2.解决办法     2.1给工程加上属性          2.1.1在工程提交之后,通过客户端 ...