外部环境数据
1.需要管理员权限
2.需要安装office2003以上完整版
3.需要安装flash reader 10.0以上
4.需要安装adodb reader;Adobe Acrobat X Pro; 8.0以上

代码比较差,仅供学习、参考

/// <summary>
/// 外部环境数据
/// 1.需要管理员权限
/// 2.需要安装office2003以上完整版
/// 3.需要安装flash reader 10.0以上
/// 4.需要安装adodb reader;Adobe Acrobat X Pro; 8.0以上
/// </summary>
public class GlobalEnvironment
{
private GlobalEnvironment()
{ } private static GlobalEnvironment _instance = new GlobalEnvironment();
public static GlobalEnvironment Instance
{
get { return _instance; }
} /// <summary>
/// 异步启动
/// </summary>
public void StartAsyc()
{
InitialTokeSource();
ExecuteTasck(StartTask);
} private void StartTask()
{
log4net.ILog _logger = log4net.LogManager.GetLogger("GlobalEnvironment");
try
{
StringBuilder sb = new StringBuilder();
SetAdminInfo(sb);
SetOfficeInfo(sb);
SetPDFInfo(sb);
SetFlashInfo(sb);
SetSystemInfo(sb);
SetDriverInfo(sb);
SetAssemblyVersionInfo(sb); _logger.FatalFormat(" 系统环境-{0}", sb.ToString());
}
catch (Exception ex)
{
_logger.ErrorFormat(" 读取系统环境错误-{0}", ex.Message);
} } #region AssemblyVersionInfo private void SetAssemblyVersionInfo(StringBuilder sb)
{
sb.AppendFormat(" >>程序集信息- ");
ProductPrj prj = new ProductPrj();
PrintStringFormat(sb, " 产品名称{0},项目名称:{1},版本号:{2}", Enum.GetName(typeof(ProductType), prj.ProductType)
, Enum.GetName(typeof(BranchType), prj.BranchType)
, prj.Version);
}
#endregion #region DirverInfo
private void SetDriverInfo(StringBuilder sb)
{
sb.AppendFormat(" >>硬盘信息- ");
string exePath = AppDomain.CurrentDomain.BaseDirectory;
DriveInfo driver = DriveInfo.GetDrives().FirstOrDefault(d => exePath.StartsWith(d.Name)); StringBuilder sbDriver = new StringBuilder();
if (driver != null)
{
sbDriver.AppendFormat("Drive {0}; ", driver.Name);
sbDriver.AppendFormat(" File type: {0}; ", driver.DriveType);
if (driver.IsReady == true)
{
sbDriver.AppendFormat(" 驱动器的卷标: {0}; ", driver.VolumeLabel);
sbDriver.AppendFormat(" 文件系统的名称: {0}; ", driver.DriveFormat);
sbDriver.AppendFormat(" 可用空闲空间总量:{0:N} bytes; ", driver.TotalFreeSpace);
sbDriver.AppendFormat(" 存储空间的总大小:{0:N} bytes; ", driver.TotalSize);
} } PrintStringFormat(sb, @" >>应用程序执行路径{0},{1} ", exePath, sbDriver.ToString());
}
#endregion #region SystemInfo
private void SetSystemInfo(StringBuilder sb)
{
sb.AppendFormat(" >>系统信息- ");
const int nChars = ;
string flag = "$";
StringBuilder Buff = new StringBuilder(nChars);
GetWindowsDirectory(Buff, nChars);
sb.AppendFormat(" Windows路径:{0}; ", Buff.ToString());
GetSystemDirectory(Buff, nChars);
sb.AppendFormat(" 系统路径:{0}; ", Buff.ToString());
sb.AppendFormat(" 系统版本:{0}; ", GetOSType());
sb.AppendFormat(" 计算机的名称:{0}; ", Environment.MachineName);
sb.AppendFormat(" 当前系统是否为 64 位系统:{0}; ", Environment.Is64BitOperatingSystem);
sb.AppendFormat(" 当前进程是否为 64 位进程:{0}; ", Environment.Is64BitProcess); sb.AppendFormat(" >>cpu信息- ");
///调用GetSystemInfo函数获取CPU的相关信息
CPU_INFO CpuInfo;
CpuInfo = new CPU_INFO();
GetSystemInfo(ref CpuInfo);
sb.AppendFormat(" 逻辑处理器{0}个; ", CpuInfo.dwNumberOfProcessors.ToString());
sb.AppendFormat(" CPU的类型为{0}; ", CpuInfo.dwProcessorType.ToString());
sb.AppendFormat(" CPU的速度为{0}GHz; ", CPUSpeed().ToString()); sb.AppendFormat(" >>内存信息- ");
///调用GlobalMemoryStatus函数获取内存的相关信息
MEMORY_INFO MemInfo;
MemInfo = new MEMORY_INFO();
GlobalMemoryStatus(ref MemInfo);
sb.AppendFormat(" 已经使用内存大小{0:N}%; ", MemInfo.dwMemoryLoad);
sb.AppendFormat(" 可用交换文件大小有{0:N}字节; ", MemInfo.dwAvailPageFile);
sb.AppendFormat(" 可使用的物理内存有{0:N}字节; ", MemInfo.dwAvailPhys);
sb.AppendFormat(" 可使用的虚拟内存有{0:N}字节; ", MemInfo.dwAvailVirtual);
sb.AppendFormat(" 交换文件总大小为{0:N}字节; ", MemInfo.dwTotalPageFile);
sb.AppendFormat(" 物理内存共有{0:N}字节; ", MemInfo.dwTotalPhys);
sb.AppendFormat(" 虚拟内存共有{0:N}字节; ", MemInfo.dwTotalVirtual);
sb.Replace(flag, MemInfo.dwLength.ToString()); } public float CPUSpeed()
{
ManagementObject Mo = new ManagementObject("Win32_Processor.DeviceID='CPU0'");
uint sp = (uint)(Mo["CurrentClockSpeed"]);
Mo.Dispose();
return Convert.ToSingle(sp) / ;
} public static string GetOSType()
{
//定义系统版本
Version ver = System.Environment.OSVersion.Version;
string OSType = "";
//Major主版本号
//Minor副版本号
if (ver.Major == && ver.Minor == )
{
OSType = " Windows 2000 ";
}
else if (ver.Major == && ver.Minor == )
{
OSType = " Windows XP ";
}
else if (ver.Major == && ver.Minor == )
{
OSType = " Windows 2003/Windows XP 64-Bit Edition/Windows Server 2003 R2 ";
}
else if (ver.Major == && ver.Minor == )
{
OSType = " Windows Vista/Windows Server 2008 ";
}
else if (ver.Major == && ver.Minor == )
{
OSType = " Windows7/Windows Server 2008 R2 ";
}
else if (ver.Major == && ver.Minor == )
{
OSType = " Windows8/Windows Server 2012 ";
}
else if (ver.Major == && ver.Minor == )
{
OSType = " Windows8.1/Windows Server 2012 R2 ";
}
else
{
OSType = string.Format("未知:major:{0},minor{1}", ver.Major, ver.Minor);
}
return OSType;
} [DllImport("kernel32")]
public static extern void GetWindowsDirectory(StringBuilder WinDir, int count);
[DllImport("kernel32")]
public static extern void GetSystemDirectory(StringBuilder SysDir, int count);
[DllImport("kernel32")]
public static extern void GetSystemInfo(ref CPU_INFO cpuinfo);
[DllImport("kernel32")]
public static extern void GlobalMemoryStatus(ref MEMORY_INFO meminfo);
[DllImport("kernel32")]
public static extern void GetSystemTime(ref SYSTEMTIME_INFO stinfo);
//定义CPU的信息结构
[StructLayout(LayoutKind.Sequential)]
public struct CPU_INFO
{
public uint dwOemId;
public uint dwPageSize;
public uint lpMinimumApplicationAddress;
public uint lpMaximumApplicationAddress;
public uint dwActiveProcessorMask;
public uint dwNumberOfProcessors;
public uint dwProcessorType;
public uint dwAllocationGranularity;
public uint dwProcessorLevel;
public uint dwProcessorRevision;
}
//定义内存的信息结构
[StructLayout(LayoutKind.Sequential)]
public struct MEMORY_INFO
{
public uint dwLength;
public uint dwMemoryLoad;
public uint dwTotalPhys;
public uint dwAvailPhys;
public uint dwTotalPageFile;
public uint dwAvailPageFile;
public uint dwTotalVirtual;
public uint dwAvailVirtual;
}
//定义系统时间的信息结构
[StructLayout(LayoutKind.Sequential)]
public struct SYSTEMTIME_INFO
{
public ushort wYear;
public ushort wMonth;
public ushort wDayOfWeek;
public ushort wDay;
public ushort wHour;
public ushort wMinute;
public ushort wSecond;
public ushort wMilliseconds;
}
#endregion #region IsAdministrator
public void SetAdminInfo(StringBuilder sb)
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
this.IsAdministrator = principal.IsInRole(WindowsBuiltInRole.Administrator); PrintStringFormat(sb, "admin: {0}", this.IsAdministrator ? "管理员" : "非管理员");
} public bool IsAdministrator { get; private set; }
#endregion #region office
private const string RegOfficeKey = @"Software\Microsoft\Windows\Shell\AttachmentExecute\{0002DF01-0000-0000-C000-000000000046}";
private void SetOfficeInfo(StringBuilder sb)
{
string wordVersion = "";
string excelVersion = "";
string pptVersion = ""; if (IsAdministrator)
{
wordVersion = GetMajorVersion(RegisterValue("winword.exe"));
excelVersion = GetMajorVersion(RegisterValue("excel.exe"));
pptVersion = GetMajorVersion(RegisterValue("powerpnt.exe"));
} this.WordEable = wordVersion == "" ? false : true;
this.ExcelEable = excelVersion == "" ? false : true;
this.PPTEable = pptVersion == "" ? false : true; PrintStringFormat(sb, "word: {0}", wordVersion);
PrintStringFormat(sb, "excel: {0}", excelVersion);
PrintStringFormat(sb, "ppt: {0}", pptVersion);
} private string GetMajorVersion(string _path)
{
string toReturn = "";
if (File.Exists(_path))
{
try
{
FileVersionInfo _fileVersion = FileVersionInfo.GetVersionInfo(_path);
toReturn = _fileVersion.FileMajorPart.ToString();
}
catch
{ }
}
return toReturn;
}
#endregion #region pdf
private void SetPDFInfo(StringBuilder sb)
{
string path = RegisterValue("AcroRd32.exe");
if (string.IsNullOrEmpty(path)) path = RegisterValue("AcroDist.exe");
PrintStringFormat(sb, "pdf: {0}", path); this.PdfEable = path == "" ? false : true;
}
#endregion #region flash
private void SetFlashInfo(StringBuilder sb)
{
string version = "";
version = GetAppVersion("ShockwaveFlash.ShockwaveFlash", (t, o) =>
{
return o.GetType().InvokeMember("GetVariable", BindingFlags.InvokeMethod,
null, o, new object[] { "$version" }).ToString();
});
PrintStringFormat(sb, "flash player: {0}", version); if (version != "")
{
version = version.Replace("WIN", "").Trim();
string[] va = version.Split(',');
int v1 = ;
if (va.Length > )
{
int.TryParse(va[], out v1);
}
if (v1 > )
this.SwfEnable = true;
} }
#endregion #region taskecancel
private CancellationTokenSource _tokenSource; private void InitialTokeSource()
{
_tokenSource = new CancellationTokenSource();
} private void CancelTokeSource()
{
_tokenSource.Cancel();
} private void ExecuteTasck(Action function)
{
TaskFactory taskFactory = new TaskFactory();
CancellationToken token = _tokenSource.Token; taskFactory.StartNew(() =>
{
if (token.IsCancellationRequested)
{
token.ThrowIfCancellationRequested();//强制取消 并不会让TaskTest1停止执行
}
function();
}, token);
} private Task<TResult> ExecuteTasck<TResult>(Func<TResult> function)
{
TaskFactory taskFactory = new TaskFactory();
CancellationToken token = _tokenSource.Token; return taskFactory.StartNew<TResult>(() =>
{
if (token.IsCancellationRequested)
{
token.ThrowIfCancellationRequested();//强制取消 并不会让TaskTest1停止执行
}
return function();
}, token);
} private Task<TResult> ExecuteTasck<TResult>(Func<object, TResult> function, object param)
{
TaskFactory taskFactory = new TaskFactory();
CancellationToken token = _tokenSource.Token; return taskFactory.StartNew<TResult>((p) =>
{
if (token.IsCancellationRequested)
{
token.ThrowIfCancellationRequested();//强制取消 并不会让TaskTest1停止执行
}
return function(p);
}, param, token);
}
#endregion #region register
private const string RegKey = @"Software\Microsoft\Windows\CurrentVersion\App Paths";
private string RegisterValue(string _key)
{
string path = "";
RegistryKey _mainKey = Registry.CurrentUser;
try
{
_mainKey = _mainKey.OpenSubKey(RegKey + "\\" + _key, false);
if (_mainKey != null)
{
path = _mainKey.GetValue(string.Empty).ToString();
}
}
catch
{ } //if not found, looks inside LOCAL_MACHINE:
_mainKey = Registry.LocalMachine;
if (string.IsNullOrEmpty(path))
{
try
{
_mainKey = _mainKey.OpenSubKey(RegKey + "\\" + _key, false);
if (_mainKey != null)
{
path = _mainKey.GetValue(string.Empty).ToString();
}
}
catch
{
}
} if (_mainKey != null)
_mainKey.Close();
return path;
}
#endregion #region version
private string GetAppVersion(string progid, Func<Type, object, string> getVersionMethod)
{
try
{
Type type = Type.GetTypeFromProgID(progid);
if (type != null)
{
dynamic obj = Activator.CreateInstance(type);
var versionString = getVersionMethod(type, obj); if (progid == "Word.Application") obj.Quit(false);
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
return versionString;
}
}
catch (Exception ex)
{
}
return "";
}
#endregion #region print
private void PrintStringFormat(StringBuilder sb, string v, params string[] p)
{
sb.AppendFormat(v, p);
sb.Append(" ; ");
}
#endregion #region enable
public bool WordEable { get; private set; }
public bool ExcelEable { get; private set; }
public bool PPTEable { get; private set; }
public bool PdfEable { get; set; }
public bool SwfEnable { get; private set; } ///// <summary>
/////检测资源控件是否可用
///// </summary>
///// <param name="func"></param>
//public void ResCheckEnable(Func<Tuple<bool, bool, bool, bool, bool>> func)
//{
// ExecuteTasck(() => {
// Tuple<bool, bool, bool, bool, bool> tuple = func();
// WordEable = tuple.Item1;
// ExcelEable = tuple.Item2;
// PPTEable = tuple.Item3;
// PdfEable = tuple.Item4;
// SwfEnable = tuple.Item5;
// });
//} #endregion }

C#:获取环境信息的更多相关文章

  1. golang 获取环境信息

    os.Environ() os.Getenv("TMP")

  2. .NET Core 获取程序运行环境信息与反射的应用

    目录 RuntimeInformation.Environment 获取信息 反射获取信息 获取某个属性的值以及别名 反射获取信息 使用 总结 笔者的九篇反射系统文章已经完结,但是笔者会持续更新反射在 ...

  3. JDK7和JDK8一些重要新特性

    jdk7新特性(部分) switch支持字符串 List AutoCloseable接口实现自动关闭,在try()中 新增获取环境信息的工具方法,getJavaHomeDir,getUserHomeD ...

  4. python网络编程【四】(域名系统)

    域名系统(DNS)是一个分布式的数据库,它主要用来把主机名转换成IP地址.DNS以及相关系统之所以存在,主要有以下两个原因: (1).它们可以使人们比较容易地记住名字. (2).它允许服务器改变IP地 ...

  5. PHP内核学习(一)SAPI

    学习PHP-src之前,我准备了一份源文件: GitHub下载->https://github.com/helingfeng/php-src 简单分析一下源码的目录结构: 1. root根目录下 ...

  6. ORACLE AUTOMATIC STORAGE MANAGEMENT翻译-第二章 ASM instance(1)

    第二章  ASM INSTANCE ASM的类型,例如可以: 10g后ORACLE instance 类型增加了一个ASM种类.参数INSTANCE_TYPE=ASM进行设置. ASM实例启动命令: ...

  7. Web Builder

    Web Builder http://www.doc88.com/p-1748774598960.html 初次接触Infopath,我就被它的强大的功能,灵活的表单制作方式,全面对Web Servi ...

  8. 【Spring源码分析】非懒加载的单例Bean初始化前后的一些操作

    前言 之前两篇文章[Spring源码分析]非懒加载的单例Bean初始化过程(上篇)和[Spring源码分析]非懒加载的单例Bean初始化过程(下篇)比较详细地分析了非懒加载的单例Bean的初始化过程, ...

  9. ROS机器人程序设计(原书第2版)补充资料 (柒) 第七章 3D建模与仿真 urdf Gazebo V-Rep Webots Morse

    ROS机器人程序设计(原书第2版)补充资料 (柒) 第七章 3D建模与仿真 urdf Gazebo V-Rep Webots Morse 书中,大部分出现hydro的地方,直接替换为indigo或ja ...

随机推荐

  1. Thinking Of Matrix

    http://blog.163.com/bzm_square/blog/static/9355546320129582254842/ PS: 一种有关于矩阵的思维方法.....WiKi 向量空间,不定 ...

  2. asp.net identity 3.0.0 在MVC下的基本使用 序言

    本人也尚在学习使用之中,错误之处请大家指正. 开发环境:vs2015 UP1   项目环境:asp.net 4.6.1   模板为:asp.net 5 模板     identity版本为:asp.n ...

  3. swift-懒加载

    override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.cyan self.navi ...

  4. webrtc初识

    最近由于项目的需求,开始接触了webrtc这个东西.没想到这东西的门槛还是蛮高的,接下来分享一下我所踩过的坑,希望对以后初次接触这个东西的人有所帮助. webrtc官网 第一步当然是看官方主页了(ww ...

  5. ASP.Net一键自动化更新代码、编译、合并dll、压缩js、css、混淆dll、zip打包、发布到测试环境的bat批处理

    不废话,直接代码: D: cd D:\src\testproj\PrecompiledWeb svn revert ../ -R svn update .. rmdir BS /S /Q C:\Win ...

  6. oracle 常用函数【转】

    常用Oracle函数 SQL中的单记录函数 1.ASCII 返回与指定的字符对应的十进制数; SQL> select ascii('A') A,ascii('a') a,ascii('0') z ...

  7. Ionic2 开发环境搭建

    Ionic2开发环境要求: Nodejs V4.5.0 Nodejs自带 Npm V2.15.9 同上 Ionic V2.1.0 安装最新ionic即可 Angular2 V2正式版 同上 说明:以上 ...

  8. !+"\v1" 能判断浏览器类型吗?

    我在 http://www.iefans.net/ie-setattribute-bug/ 中看到如此判断是否是IE,if(!+"\v1"){IE代码}else{其他浏览器代码}, ...

  9. python不是内部或外部命令

    原因是环境变量没有添加. 比如python安装再C:\Python27 环境变量path增加C:\Python27即可,不需重启. 但是之前报错的cmd窗口需要重新打开再执行python命令

  10. 显示python已安装模块及路径,添加修改模块搜索路径

    在python交互模式下输入: help('modules') #可以显示出已安装的模块 在python交互模式下输入: import sys sys.path #可以显示出模块搜索路径 增加搜索路径 ...