使用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 = ;
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共享机制的更多相关文章
- linux目录和Windows目录对比
linux目录和Windows目录对比 我们应该知道 Windows 有一个默认的安装目录专门用来安装软件.Linux 的软件安装目录也应该是有讲究的,遵循这一点,对后期的管理和维护也是有帮助的. / ...
- 控制Arduino的利器-Windows Remote Arduino
1. 概述 相信很多朋友已经在玩 Arduino了,而且一般都是使用官方的Arduino IDE来写程序控制Arduino硬件.为了能够实现更加方便的控制,微软在Windows IoT计划中推出了Wi ...
- [转] 控制Arduino的利器-Windows Remote Arduino
原文地址:控制Arduino的利器-Windows Remote Arduino 1. 概述 相信很多朋友已经在玩 Arduino了,而且一般都是使用官方的Arduino IDE来写程序控制Ardui ...
- QT正则表达式学习(Windows目录禁止九个字符)
exp 正则表达式30分钟入门教程 http://deerchao.net/tutorials/regex/regex.htm 元字符 .*^\d\b\s,当然还有\,还有中括号[] .是一个元字符, ...
- [Windows Phone] 在 Windows Phone 8 控制闪光灯
原文:[Windows Phone] 在 Windows Phone 8 控制闪光灯 ? 前言 在 Windows Phone 如果想要控制闪光灯,该怎麽做?在 Windows Phone 8 提供类 ...
- Windows服务器如何查看共享目录信息
查看Windows服务器上的共享目录的相关信息,可以使用两种方式: 1:命令net share 查看: 2:通过计算机管理的Shared Folders查看
- Delphi调用API函数获取Windows目录信息、获取System目录信息、获取Temp临时文件目录信息
var Str1, Str2: Array[..Max_Path]of Char;//开辟缓冲区 Str3: Array[..]of Char; begin GetWindowsDirectory(@ ...
- Linux 挂载windows目录
1.默认情况下,Linux服务器会装有samba-client,但是没有装samba-server.但是访问Windows系统共享,安装有samba-client就可以了. [root@test ~] ...
- 将windows目录共享到linux
1.将windows目录共享 2.安装cifs 3. mount -t cifs -o username=电脑登陆用户名,password=电脑登陆用户密码 //127.0.0.1/abc /var ...
随机推荐
- javascript design patterns
http://jsdesignpatterns.com/ http://www.joezimjs.com/tag/design-patterns/ http://codecube.net/#archi ...
- MSP430的IO口模拟I2C总线对AT24C25进行读写程序
功能: 实现MSP430口线模拟I2C总线协议与24C04通信. ** 描述: 主系统工作时钟为12MHz,I2C工 ...
- JS实现点击按钮,自增输入框个数
<html> <head> <script language="javascript"> var i=0; function addinput( ...
- Unity NGUI中动态添加和删除sprite
(以后,参考链接和作者将在文章首部给出,转载请保留此部分内容) 参考链接:http://www.narkii.com/club/thread-299977-1.html,作者:纳金网 比巴卜: 参考链 ...
- 搜索(DLX):HDU 3663 Power Stations
Power Stations Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)To ...
- [Java] JavaMail 发送 html 格式、带附件的邮件
本案例演示发送 html 格式,可带附件的邮件发送.发送纯文本邮件的例子可参照上一篇博文JavaMail 简单案例. EmailHelper, Email 的帮助类,向帮助类提供 SMTP 服务器域名 ...
- DNA repair - HDU 2457(自动机+dp)
题目大意:给你N个DNA的串,也就是至包含'A','T','G','C'四种碱基的,这些给定的串都是带有遗传病的,然后给你一个不会超过1000的串,问你至少几个地方才能让这个串不包含遗传病,如果不论怎 ...
- 【Cocos2d-X开发学习笔记】第27期:游戏背景之贴图地图类(CCTileMapAtlas)的使用
本系列学习教程使用的是cocos2d-x-2.1.4(最新版为3.0alpha0-pre) ,PC开发环境Windows7,C++开发环境VS2010 一.贴图地图类CCTileMapAtlas 除了 ...
- 视频监控之VSCloud版本计划
下个版本会加入 1.人脸检测和人脸识别功能 2. 车牌识别. https://code.google.com/p/vscloud/ 下载连接 https://sourceforge.net/proje ...
- 大数据应用之:MongoDB从入门到精通你不得不知的21个为什么?
一.引言: 互联网的发展和电子商务平台的崛起,催生了大数据时代的来临,作为大数据典型开发框架的MongoDB成为了No-sql数据库的典型代表.MongoDB从入门到精通你不得不知的21个为什么专为大 ...