首页 > 其他分享 >安装使用服务

安装使用服务

时间:2023-10-20 17:23:41浏览次数:36  
标签:服务 string args serviceName static serviceFilePath 使用 安装 ex

internal class Program
    {

        static string configDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "WallpaperService");
        static string serviceFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "WallpaperService") + @"\WallpaperService.exe";
        static string sourceFolderPath = AppDomain.CurrentDomain.BaseDirectory + @"WindowsService"; // 替换为源文件夹路径
        static string serviceName = "WallpaperService";
        static string programPath = AppDomain.CurrentDomain.BaseDirectory + @"WallpaperServiceWPF.exe";
        public static void WriteLog(params string[] msg)
        {
            string filePath = AppDomain.CurrentDomain.BaseDirectory + "Log";
            if(!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            string logPath = AppDomain.CurrentDomain.BaseDirectory + "Log\\log2.txt";
            File.AppendAllLines(logPath, msg);
        }
        static void Main(string[] args)
        {
            //WriteLog(args[0]);
            if(args[0] == "InstallationServer")
            {
                InstallCommand(serviceFilePath, serviceName);

            }
            else if(args[0] == "UpdateServer")
            {
                SendUninstallCommand(serviceFilePath);
                // 删除替换
                File.Copy(args[1], serviceFilePath, true);
                //
                InstallCommand(serviceFilePath, serviceName);
            }
            else if(args[0] == "UninstallServer")
            {
                RecevicedUninstallCommand(args[1], serviceName);
            }
            else if(args[0] == "DeleteServer")
            {
                SendUninstallCommand(serviceFilePath);
                //File.Delete(args[1]);
                //Directory.Delete(serviceFilePath, true);
                //Console.WriteLine("目录删除成功!");

                string processName = "WallpaperServiceWPF"; // 要检测的进程的名称

                // 检测进程是否已经启动
                if(IsProcessRunning(processName))
                {
                    Console.WriteLine($"{processName} 已经启动,将关闭它。");
                    CloseProcess(processName);
                }

                // 获取目录中的所有文件
                string[] files = Directory.GetFiles(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "WallpaperService"));

                // 遍历并删除每个文件
                foreach(string file in files)
                {
                    try
                    {
                        File.Delete(file);
                    }
                    catch(Exception ex)
                    {
                    }
                }
            }
            else if(args[0] == "DeletingFiles")
            {
                // 获取目录中的所有文件
                string[] files = Directory.GetFiles(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "WallpaperService"));

                //string[] files = Directory.GetFiles(args[1]);

                // 遍历并删除每个文件
                foreach(string file in files)
                {
                    try
                    {
                        File.Delete(file);
                    }
                    catch(Exception ex)
                    {
                    }
                }
            }
            else if(args[0] == "ReplacingFiles")
            {
                //string[] p = args[1].Split('&');
                DirectoryInfo directoryInfo = new DirectoryInfo(configDir);
                if(!directoryInfo.Exists)
                {
                    directoryInfo.Create();
                }
                string[] files = Directory.GetFiles(sourceFolderPath);
                foreach(string sourceFilePath in files)
                {
                    try
                    {
                        // 构建目标文件路径
                        string fileName = Path.GetFileName(sourceFilePath);
                        string destinationFilePath = Path.Combine(configDir, fileName);

                        // 复制文件
                        File.Copy(sourceFilePath, destinationFilePath, true); // 第三个参数表示是否覆盖目标文件
                        Console.WriteLine($"复制文件:{fileName}");
                    }
                    catch(Exception ex)
                    {
                        //WriteLog(ex.Message);
                    }
                }
                File.Copy(AppDomain.CurrentDomain.BaseDirectory + @"WallpaperServiceWPF.exe", configDir + @"\WallpaperServiceWPF.exe", true);
            }
            else if(args[0]== "InstallServicesOneStep")
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(configDir);
                if(!directoryInfo.Exists)
                {
                    directoryInfo.Create();
                }
                if(IsServiceExisted("WallpaperService"))
                {
                    SendUninstallCommand(serviceFilePath);
                    string processName = "WallpaperServiceWPF"; // 要检测的进程的名称

                    // 检测进程是否已经启动
                    if(IsProcessRunning(processName))
                    {
                        Console.WriteLine($"{processName} 已经启动,将关闭它。");
                        CloseProcess(processName);
                    }
                    string[] files = Directory.GetFiles(sourceFolderPath);
                    foreach(string sourceFilePath in files)
                    {
                        try
                        {
                            // 构建目标文件路径
                            string fileName = Path.GetFileName(sourceFilePath);
                            string destinationFilePath = Path.Combine(configDir, fileName);

                            // 复制文件
                            File.Copy(sourceFilePath, destinationFilePath, true); // 第三个参数表示是否覆盖目标文件
                            Console.WriteLine($"复制文件:{fileName}");
                        }
                        catch(Exception ex)
                        {

                        }
                    }
                    File.Copy(programPath, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "WallpaperService") + @"\WallpaperServiceWPF.exe", true);
                    InstallCommand(serviceFilePath, serviceName);
                }
                else
                {
                    string[] files = Directory.GetFiles(sourceFolderPath);
                    foreach(string sourceFilePath in files)
                    {
                        try
                        {
                            // 构建目标文件路径
                            string fileName = Path.GetFileName(sourceFilePath);
                            string destinationFilePath = Path.Combine(configDir, fileName);

                            // 复制文件
                            File.Copy(sourceFilePath, destinationFilePath, true); // 第三个参数表示是否覆盖目标文件
                            Console.WriteLine($"复制文件:{fileName}");
                        }
                        catch(Exception ex)
                        {

                        }
                    }
                    File.Copy(programPath, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "WallpaperService") + @"\WallpaperServiceWPF.exe", true);

                    InstallCommand(serviceFilePath, serviceName);
                }
            }
        }
        static bool IsProcessRunning(string processName)
        {
            Process[] processes = Process.GetProcessesByName(processName);
            return processes.Length > 0;
        }

        // 关闭进程
        static void CloseProcess(string processName)
        {
            Process[] processes = Process.GetProcessesByName(processName);
            foreach(var process in processes)
            {
                process.CloseMainWindow(); // 尝试发送关闭窗口命令
                process.WaitForExit(5000); // 等待最多5秒钟,确保进程关闭
                if(!process.HasExited)
                {
                    // 如果进程仍然没有关闭,强制终止它
                    process.Kill();
                    process.WaitForExit();
                }
            }
        }

        //执行安装命令
        public static void InstallCommand(string serviceFilePath, string serviceName)
        {
            InstallService(serviceFilePath);
            ServiceStart(serviceName);

        }

        //发送卸载命令
        public static void SendUninstallCommand(string serviceFilePath)
        {
            ProcessStartInfo startInfo = new ProcessStartInfo
            {
                FileName = Assembly.GetExecutingAssembly().Location,
                Arguments = string.Join(" ", new string[] { "UninstallServer", serviceFilePath }),
                Verb = "runas", // 使用"runas"来请求管理员权限
                UseShellExecute = true,
                CreateNoWindow = true,
                WindowStyle = ProcessWindowStyle.Hidden
            };
            Process p = Process.Start(startInfo);
            p.WaitForExit();
            //Process p = Process.Start(Assembly.GetExecutingAssembly().Location, string.Join(" ", new string[] { "UninstallServer", serviceFilePath }));
            //p.WaitForExit();
        }

        //接受卸载命令
        public static void RecevicedUninstallCommand(string serviceFilePath, string serviceName)
        {
            ServiceStop(serviceName);
            UninstallService(serviceFilePath);
        }


        #region 方法封装


        //判断服务是否存在

        private static bool IsServiceExisted(string serviceName)
        {
            try
            {
                ServiceController[] services = ServiceController.GetServices();
                foreach(ServiceController sc in services)
                {
                    if(sc.ServiceName.ToLower() == serviceName.ToLower())
                    {
                        return true;
                    }
                }
                return false;
            }
            catch(Exception ex)
            {
                return false;
            }
        }

        //安装服务

        private static void InstallService(string serviceFilePath)
        {
            try
            {
                using(AssemblyInstaller installer = new AssemblyInstaller())
                {
                    installer.UseNewContext = true;
                    installer.Path = serviceFilePath;
                    IDictionary savedState = new Hashtable();
                    installer.Install(savedState);
                    installer.Commit(savedState);
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
            }

        }

        //卸载服务

        private static void UninstallService(string serviceFilePath)
        {
            try
            {
                using(ServiceInstaller ServiceInstallerObj = new ServiceInstaller())
                {
                    InstallContext Context = new InstallContext(AppDomain.CurrentDomain.BaseDirectory + "\\uninstalllog.log", null);
                    ServiceInstallerObj.Context = Context;
                    ServiceInstallerObj.ServiceName = "WallpaperService";
                    ServiceInstallerObj.Uninstall(null);
                }
            }
            catch(Exception ex)
            {
            }
        }

        //启动服务

        private static void ServiceStart(string serviceName)
        {
            try
            {
                using(ServiceController control = new ServiceController(serviceName))
                {
                    if(control.Status == ServiceControllerStatus.Stopped)
                    {
                        control.Start();
                    }
                }
            }
            catch(Exception ex)
            {
            }
        }

        //停止服务

        private static void ServiceStop(string serviceName)
        {
            try
            {
                using(ServiceController control = new ServiceController(serviceName))
                {
                    if(control.Status == ServiceControllerStatus.Running)
                    {
                        control.Stop();
                    }
                }
            }

            catch(Exception ex)
            {
            }
        }

        #endregion





    }

注意,服务安装卸载要在管理员权限下进行

// 要传递的参数
                string arguments = $"InstallationServer \"{configDir + @"\WallpaperService.exe"}\"";
                // 创建一个启动进程的 ProcessStartInfo 对象
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    FileName = AppDomain.CurrentDomain.BaseDirectory + @"ConsoleApp2.exe",
                    Arguments = arguments,
                    Verb = "runas", // 使用"runas"来请求管理员权限
                    UseShellExecute = true,
                    CreateNoWindow = true
                };
                try
                {
                    // 启动进程
                    Process.Start(startInfo);
                }
                catch(Exception ex)
                {
                    // 处理异常
                    Console.WriteLine("Error: " + ex.Message);
                }

主程序调用

标签:服务,string,args,serviceName,static,serviceFilePath,使用,安装,ex
From: https://www.cnblogs.com/wangjintao99/p/17777567.html

相关文章

  • 零基础学习CAE——Hypermesh的使用技巧
    Hypermesh是一款强大的有限元前后处理软件,用于建模、网格划分、后处理和优化分析。以下是一些Hypermesh使用技巧:  1. 界面布局:在开始使用Hypermesh之前,可以调整界面布局以适应个人喜好。可以通过"View"菜单中的选项来自定义工具栏、视图和面板的位置和大小。 2. 快捷键......
  • JMeter 使用 http长连接
    如果需要在JMeter通过http长连接发送请求,首先需要选择了UseKeepAlive长连接协议,虽然默认是勾选的,但也需要确认一下。除了选择了UseKeepAlive长连接协议,还需要在Advanceed高级选项面板,选择HttpClient4类型的HttpRequest请求实现。在即使选择了UseKeepAlive长连......
  • 使用Grafana + jmx 监控 kafka3.5 的过程
    使用Grafana+jmx监控kafka3.5的过程摘要周五一边进行数据库监控,同时想着部署一套监控系统.能够监控一下kafka等中间件结果不想自己遇到了很多坑.下午有同事语音告诉自己一些排查问题的方式与方法.自己又多花了半个小时才将数据捞出来.感觉自己对很多工具的使用还......
  • 游戏服务器性能压测实战分析
    今天遇到一个性能压测的问题,也是很多同学做游戏服务器开发经常会遇到的,今天记录一下分享给大家。 性能压测遇到的问题 服务器硬件情况: 8核16G服务器,  带宽1000M,redis假设在独立的内网云服务上,通过内网连接;性能压测:压测功能接口1: 查询当前服务器的时间戳,并返......
  • TC10 异常退出无法正常使用一例分析
    1.主要现象,客户TC系统正常使用,近期未做bmide和itk代码部署更新,突然频繁出现“tcserver.exe异常崩溃”造成TC无法使用。2.尝试解决的处理2.1登录系统,使用dba账户进行可能异常的操作,发现异常无法准确复现,各种操作都可能会出现:查询、创建、展开BOM、搜索引用等。 2.2登录查看日......
  • Docker 安装bookstack
    Docker安装bookstack(环境centos)docker安装自行百度yuminstall-ydockerMYSQL安装#拉取镜像dockerpullmysql#创建数据存放位置mkdir-p/var/own/datadirmkdir-p/var/own/conf#在/var/own/conf新建my.cnf并填写内容vimy.cnf#创建mysql容器dockerrun--na......
  • 第二章 第三四节 线程池技术以及使用 上
    线程池技术介绍1.线程池的作用​ 避免重复不断地创建、销毁线程,浪费系统资源​ PS:线程池可以成一个容器​ 多线程业务:发短信或者发送邮件(异步任务);请求第三方接口(异步任务);2.线程池原理​3.线城池的销毁​ shutDown等待正在执行任务执行完毕,才会销毁​ shutDownNow......
  • STM32 EEPROM_Emulation 保存数据使用注意事项
    1目的:stm32官方提供flash模拟eeprom的代码例子,为了能给产品添加数据保存功能,可以改造该例子迅速完成数据保存的功能。示例代码路径:C:\Users\rd-yhzhang\STM32Cube\Repository\STM32Cube_FW_F1_V1.8.5\Projects\STM32F103RB-Nucleo\Applications\EEPROM\EEPROM_Emulation。2......
  • Mac OS安装Python的pip
    最近牛牛的同学在学习python,但当他使用numpy时出现了报错(。•́︿•̀。)原因为他的python没有numpy这个库(这个故事很典)。然鹅雪上加霜的是,他的电脑是Mac,没有Windows的cmd...牛牛还没碰过苹果电脑,后面通过查找百度发现在苹果里这玩意儿叫Terminal,经历千辛万苦打开Terminal并开始pip后,......
  • Win2012 搭建NTP 服务器
    1、regedit1、修改HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Config中"AnnounceFlags"值为52、修改HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer中"Enabled"值为12、servi......