using Microsoft.Win32;
using System.Diagnostics;
using System.Security.AccessControl;
namespace ConnectPoint
{
class RegistryHelper
{
///
/// 读取指定名称的注册表的值
///
/// 注册表顶级节点
/// 注册表项所在路径
/// 注册表项名称
/// 注册表项值
public string GetRegistryData(RegistryKey root, string subkey, string name)
{
string registData = "";
RegistryKey myKey = root.OpenSubKey(subkey,
RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.QueryValues);
if (myKey != null)
{
registData = myKey.GetValue(name).ToString();
}
return registData;
}
///
/// 创建或修改指定名称的注册表的值
///
/// 注册表顶级节点
/// 注册表项所在路径
/// 注册表项名称
/// 注册表项值
/// 值类型
public void SetRegistryData(RegistryKey root, string subkey, string name, string value, RegistryValueKind valueKind)
{
RegistryKey aimdir = root.CreateSubKey(subkey,
RegistryKeyPermissionCheck.ReadWriteSubTree);
aimdir.SetValue(name, value, valueKind);
}
///
/// 删除指定名称的注册表项
///
/// 注册表顶级节点
/// 注册表项所在路径
/// 注册表项名称
public void DeleteRegist(RegistryKey root, string subkey, string name)
{
string[] subkeyNames;
RegistryKey myKey = root.OpenSubKey(subkey,
RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.SetValue);
subkeyNames = myKey.GetSubKeyNames();
foreach (string aimKey in subkeyNames)
{
if (aimKey == name)
myKey.DeleteSubKeyTree(name);
}
}
///
/// 判断指定名称的注册表项是否存在
///
/// 注册表顶级节点
/// 注册表项所在路径
/// 注册表项名称
///
public bool IsRegistryExist(RegistryKey root, string subkey, string name)
{
bool _exit = false;
string[] subkeyNames;
RegistryKey myKey = root.OpenSubKey(subkey,
RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.QueryValues);
subkeyNames = myKey.GetSubKeyNames();
foreach (string keyName in subkeyNames)
{
if (keyName == name)
{
_exit = true;
return _exit;
}
}
return _exit;
}
///
/// 运行Dos命令并返回结果
///
/// Dos命令
/// 进程等待时间(毫秒)
///
public static string Execute(string command, int seconds = 2000)
{
string output = ""; //输出字符串
if (command != null && !command.Equals(""))
{
Process process = new Process();//创建进程对象
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd.exe";//设定需要执行的命令
startInfo.Arguments = "/C " + command;//“/C”表示执行完命令后马上退出
startInfo.UseShellExecute = false;//不使用系统外壳程序启动
startInfo.RedirectStandardInput = false;//不重定向输入
startInfo.RedirectStandardOutput = true; //重定向输出
startInfo.CreateNoWindow = true;//不创建窗口
process.StartInfo = startInfo;
try
{
if (process.Start())//开始进程
{
if (seconds == 0)
{
process.WaitForExit();//这里无限等待进程结束
}
else
{
process.WaitForExit(seconds); //等待进程结束,等待时间为指定的毫秒
}
output = process.StandardOutput.ReadToEnd();//读取进程的输出
}
}
catch
{
}
finally
{
if (process != null)
process.Close();
}
}
return output;
}
}
}