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. cut 命令使用

    cut -d -f cut -c cut -d分隔符 -f分割后取的第几个字符串 cut -c从哪个字符开始取

  2. BZOJ 1033 杀蚂蚁

    Description 最近,佳佳迷上了一款好玩的小游戏:antbuster.游戏规则非常简单:在一张地图上,左上角是蚂蚁窝,右下角是蛋糕,蚂蚁会源源不断地从窝里爬出来,试图把蛋糕搬回蚂蚁窝.而你的任 ...

  3. BZOJ 1028 麻将

    Description 麻将是中国传统的娱乐工具之一.麻将牌的牌可以分为字牌(共有东.南.西.北.中.发.白七种)和序数牌(分为条子.饼子.万子三种花色,每种花色各有一到九的九种牌),每种牌各四张.在 ...

  4. Codeforces Round #Pi (Div. 2) ABCDEF已更新

    A. Lineland Mail time limit per test 3 seconds memory limit per test 256 megabytes input standard in ...

  5. Pen Editor

    Pen Editor

  6. 数据结构(跳跃表):NOI 2004 郁闷的出纳员

    郁闷的出纳员 [问题描述] OIER公司是一家大型专业化软件公司,有着数以万计的员工.作为一名出纳员,我的任务之一便是统计每位员工的工资.这本来是一份不错的工作,但是令人郁闷的是,我们的老板反复无常, ...

  7. poj3186 Treats for the Cows

    http://poj.org/problem?id=3186 Treats for the Cows Time Limit: 1000MS   Memory Limit: 65536K Total S ...

  8. poj2318 水题(二分+叉积)

    题目链接:http://poj.org/problem?id=2318 #include<cstdio> #include<cstring> #include<cmath ...

  9. poj1026

    题目大意:暗号 Bod 和 Alice 计划使用一种全新的编码方案,令人惊讶的是这不是一个公开的公匙密码,但是他们的编码基于密匙,在Philadelphia on February 16th他们的会议 ...

  10. CodeForces 27D - Ring Road 2 构图2-sat..并输出选择方案

        题意             n个数1~n按顺序围成一个圈...现在在某些两点间加边..边可以加在圈内或者圈外..问是否会发生冲突?如果不发生冲突..输每一条边是放圈内还是圈外.     题解 ...