安装使用服务

复制代码
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);
                }
复制代码

主程序调用

posted @   DIO·SAMA  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
点击右上角即可分享
微信分享提示