前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >WPF开发-检测软件的运行环境及运行库下载

WPF开发-检测软件的运行环境及运行库下载

作者头像
码客说
发布2021-12-12 14:37:15
1.1K0
发布2021-12-12 14:37:15
举报
文章被收录于专栏:码客码客

前言

WPF开发的基于.NET环境的应用运行时必须要有对应的环境,有时程序还需要VC环境,所以我们可以做一个检测环境的程序。

不要在自己的程序内检测,没有环境我们的程序压根运行不起来,所以我们写的环境监测的程序所依赖的.NET环境一定要尽可能低,保证在Windows上都能运行,我这里基本只考虑Win7以上所以用的.NET3.5版本

环境监测

代码语言:javascript
复制
using Microsoft.Win32;

using System.Runtime.InteropServices;

namespace env_monitor.Utils
{
    /// <summary>
    /// 以下是判断vc++版本函数
    /// </summary>
    public class EnvCheckUtil
    {
        [DllImport("msi.dll")]
        private static extern INSTALLSTATE MsiQueryProductState(string product);

        private enum INSTALLSTATE
        {
            INSTALLSTATE_NOTUSED = -7,  // component disabled
            INSTALLSTATE_BADCONFIG = -6,  // configuration data corrupt
            INSTALLSTATE_INCOMPLETE = -5,  // installation suspended or in progress
            INSTALLSTATE_SOURCEABSENT = -4,  // run from source, source is unavailable
            INSTALLSTATE_MOREDATA = -3,  // return buffer overflow
            INSTALLSTATE_INVALIDARG = -2,  // invalid function argument
            INSTALLSTATE_UNKNOWN = -1,  // unrecognized product or feature
            INSTALLSTATE_BROKEN = 0,  // broken
            INSTALLSTATE_ADVERTISED = 1,  // advertised feature
            INSTALLSTATE_REMOVED = 1,  // component being removed (action state, not settable)
            INSTALLSTATE_ABSENT = 2,  // uninstalled (or action state absent but clients remain)
            INSTALLSTATE_LOCAL = 3,  // installed on local drive
            INSTALLSTATE_SOURCE = 4,  // run from source, CD or net
            INSTALLSTATE_DEFAULT = 5,  // use default, local or source
        }

        public static bool IsInstallVc()
        {
            bool result = false;
            if (MsiQueryProductState("{01FAEC41-B3BC-44F4-B185-5E8475AEB855}") == INSTALLSTATE.INSTALLSTATE_DEFAULT)
                result = true;
            else if (MsiQueryProductState("{77EB1EA9-8E1B-459D-8CDC-1984D0FF15B6}") == INSTALLSTATE.INSTALLSTATE_DEFAULT)
                result = true;
            return result;
        }

        /// <summary>
        /// 判断.Net Framework的Version是否符合需要 (.Net Framework 版本在2.0及以上)
        /// </summary>
        /// <param name="version">
        /// 需要的版本 version = 4.5
        /// </param>
        /// <returns>
        /// </returns>
        public static bool IsInstallDotNet(string version)
        {
            string oldname = "0";
            using (RegistryKey ndpKey =
                RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, "").
                OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\"))
            {
                foreach (string versionKeyName in ndpKey.GetSubKeyNames())
                {
                    if (versionKeyName.StartsWith("v"))
                    {
                        RegistryKey versionKey = ndpKey.OpenSubKey(versionKeyName);
                        string newname = (string)versionKey.GetValue("Version", "");
                        if (string.Compare(newname, oldname) > 0)
                        {
                            oldname = newname;
                        }
                        if (newname != "")
                        {
                            continue;
                        }
                        foreach (string subKeyName in versionKey.GetSubKeyNames())
                        {
                            RegistryKey subKey = versionKey.OpenSubKey(subKeyName);
                            newname = (string)subKey.GetValue("Version", "");
                            if (string.Compare(newname, oldname) > 0)
                            {
                                oldname = newname;
                            }
                        }
                    }
                }
            }
            return string.Compare(oldname, version) > 0 ? true : false;
        }
    }
}

使用

代码语言:javascript
复制
var isInstallVc = EnvCheckUtil.IsInstallVc();
Console.WriteLine("是否安装VC:" + isInstallVc);

var isInstallNet = EnvCheckUtil.IsInstallDotNet("4.5");
Console.WriteLine("是否安装.Net4.5:" + isInstallNet);

环境库下载

工具类

代码语言:javascript
复制
using System;
using System.ComponentModel;
using System.IO;
using System.Net;

namespace env_monitor.Utils
{
    internal class FileDownloadUtil
    {
        private Action<long, long, int, string> progressAction = null;
        private Action<string, string> finishAction = null;
        private Action<string, string> errorAction = null;
        private string savepathAll = "";
        private string filetag = "";

        public static string getFilename(string url)
        {
            string filename = "";
            string[] url_arr = url.Split('/');
            if (url_arr.Length > 0)
            {
                filename = url_arr[url_arr.Length - 1];
            }

            return filename;
        }

        public void downfile(
                string url,
                string savepath,
                string filename,
                string filetag,
                Action<long, long, int, string> progressAction,
                Action<string, string> finishAction,
                Action<string, string> errorAction
            )
        {
            this.filetag = filetag;
            this.progressAction = progressAction;
            this.finishAction = finishAction;
            this.errorAction = errorAction;
            if (filename == null || filename == "")
            {
                filename = getFilename(url);
            }

            if (filename == null || filename == "")
            {
                this.errorAction("没有文件名!", this.filetag);
                return;
            }
            savepathAll = Path.Combine(savepath, filename);
            WebClient client = new WebClient();
            client.DownloadFileCompleted += client_DownloadFileCompleted;
            client.DownloadProgressChanged += client_DownloadProgressChanged;
            client.DownloadFileAsync(new Uri(url), savepathAll);
        }

        private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            finishAction(savepathAll, filetag);
        }

        private void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            long Total = e.TotalBytesToReceive;
            long Received = e.BytesReceived;
            int ProgressPercentage = e.ProgressPercentage;
            progressAction(Total, Received, ProgressPercentage, filetag);
        }
    }
}

下载

代码语言:javascript
复制
string mfileurl = "https://xhkjedu.oss-cn-huhehaote.aliyuncs.com/runtime/vc_redist.x86.exe";
string msavepath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string mfilename = FileDownloadUtil.getFilename(mfileurl);
string mfiletag = "testfile";
string mfilepathAll = System.IO.Path.Combine(msavepath, mfilename);
FileInfo fi = new FileInfo(mfilepathAll);
if (!fi.Exists)
{
  new FileDownloadUtil().downfile(
    mfileurl,
    msavepath,
    mfilename,
    mfiletag,
    (total, receive, progress, tag) =>
    {
      Console.WriteLine(tag + " 下载进度:" + progress);
    },
    (filepathAll, tag) =>
    {
      Console.WriteLine(tag + " 下载完成:" + filepathAll);
      Process.Start(filepathAll);
    },
    (err, tag) =>
    {
      Console.WriteLine(tag + " 下载出错:" + err);
    }
  );
}
else
{
  Console.WriteLine("文件已下载:" + mfilepathAll);
  Process.Start(mfilepathAll);
}

这里提供两个下载地址

VC:https://xhkjedu.oss-cn-huhehaote.aliyuncs.com/runtime/vc_redist.x86.exe .Net4.5.2:https://xhkjedu.oss-cn-huhehaote.aliyuncs.com/runtime/NDP452-KB2901907-x86-x64-AllOS-ENU.exe

安装

代码语言:javascript
复制
Process pr = new Process();//声明一个进程类对象
pr.StartInfo.FileName = mfilepathAll;
pr.Start();

还可以简单点:Process的静态方法Start();

代码语言:javascript
复制
//filiName 是你要运行的程序名,是物理路径
Process.Start(String  fileName); 
//filiName 是你要运行的程序名,是物理路径;arguments启动改程序时传递的命令行参数
Process.Start(String  fileName,string arguments)
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-12-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 环境监测
  • 环境库下载
    • 工具类
      • 下载
      • 安装
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档