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. IFrame中Session丢失的解决办法

    1.打开IIS管理器 inetmgr2.选择被嵌入iframe源站点或者目录,右键点击打开属性框3.切换到HTTP头4.添加5.自定义HTTP头名: P3P6.自定义HTTP头值: CP=" ...

  2. Canny边缘检测-Wiki

    Canny edge dector 由 John F. Canny 在1986年提出. Canny 算法的发展 Canny算法的步骤 2.1 降噪 2.2 寻找图像的亮度梯度 2.3 非极大值抑制 2 ...

  3. 转:PHP超时处理全面总结

    原文来自于:http://wulijun.github.io/2012/08/08/php-timeout-summary.html 概述 在PHP开发工作里非常多使用到超时处理的场合,我说几个场景: ...

  4. 使用 InstallShield limited edition 打包部署Outlook 2013 Office add-in插件

    原文: Outlook: Deploying an Outlook 2013 add-in (using InstallShield LE) Today I had to create an inst ...

  5. Oracle预估的基数算法

    SQL> create table t as select * from dba_objects; Table created. SQL> create index idx_t on t( ...

  6. 【HDOJ】1483 Automatic Correction of Misspellings

    水模拟题. /* 1483 */ #include <cstdio> #include <cstring> #include <cstdlib> #define M ...

  7. cscope使用

    [[]][]再加上][一共是 4 个在段落(对于 C 来讲就是函数)间跳转的命令. 总结是:1,相同就跳到函数的开头:(如果都是左括号或者都是右括号),不同就跳到函数的结尾:     { 和 } 用来 ...

  8. Android的一个自定义的动态添加Dialog类

    android里面会有自己内置的Dialog的提示框,也算是比较方便的了,但是为了省点时间,我们在项目里面添加了一个自己的Dialog类,这个类实现了能够动态的添加按钮和一些提示语句或者其他的显示效果 ...

  9. (转载)php数组添加、删除元素的方法

    (转载)http://www.phpgs.com/html/php/phpjichu/20120130440.html 带来一篇php 数组 添加元素.删除元素的方法的文章,有需要的php学习者参考下 ...

  10. VS插件 热

    1. AnkhSVN - Subversion SCC Providerhttp://ankhsvn.open.collab.net/ AnkhSVN是一个VS的Subversion 源代码管理提供者 ...