使用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 ...
随机推荐
- NXP LPC11xx I2C Slave 从机程序
/**************************************************************************** * $Id:: i2cslave.c 363 ...
- 关于如何在BCB中使用CodeGuard
作者:深圳虫 来自:深圳虫网本文来自http://www.szbug.com/disparticle.aspID=4 一. 为什么写这篇东西自己在使用BCB5写一些程序时需要检查很多东西,例如内存泄漏 ...
- Java实现Qt的SIGNAL-SLOT机制
SIGNAL-SLOT是Qt的一大特色,使用起来十分方便.在传统的AWT和Swing编程中,我们都是为要在 监听的对象上添加Listener监听器.被监听对象中保存有Listener的列表,当相关事件 ...
- “adb server is out of date. killing.... ADB server didn't ACK * failed to start daemon * ”
草泥马的adb: “adb server is out of date. killing.... ADB server didn't ACK * failed to start daemon * ” ...
- 使用next-key locks 用于搜索和索引扫描,可以防止幻读
Next-Key Locks A next-key lock is a combination of a record lock on the index record and a gap lock ...
- HDOJ(HDU) 2153 仙人球的残影(谜一样的题、、、)
Problem Description 在美丽的HDU,有一名大三的同学,他的速度是众所周知的,跑100米仅仅用了2秒47,在他跑步过程中会留下残影的哎,大家很想知道他是谁了吧,他叫仙人球,既然名字这 ...
- [已解决问题] An error occurred while automatically activating bundle com.android.ide.eclipse.adt
可以参见stackoverflow的解决方案:http://stackoverflow.com/questions/16974349/an-error-occurred-while-automatic ...
- [Locked] Sparse Matrix Multiplication
Given two sparse matrices A and B, return the result of AB. You may assume that A's column number is ...
- 《A First Course in Probability》-chaper6-随机变量的联合分布-独立性
在探讨联合分布的时候,多个随机变量之间可以是互相独立的.那么利用独立性这个性质我们就能够找到一些那些非独立随机变量没有的求解概率的方法. 对于离散型随机变量的独立联合分布: 离散型随机变量X.Y独立, ...
- zookeeper 删除snapshot和transaction log的源码解读
转载请注明源地址http://www.cnblogs.com/dongxiao-yang/p/4910059.html zookeeper具有自动清除快照日志和事务日志的工能,可以在配置文件设置aut ...