91网首页-91网页版-91网在线观看-91网站免费观看-91网站永久视频-91网站在线播放

LOGO OA教程 ERP教程 模切知識交流 PMS教程 CRM教程 開發文檔 其他文檔  
 
網站管理員

C# 設置指定程序為Windows系統服務方式運行,或者關閉指定程序在Windows系統服務

admin
2025年6月2日 18:49 本文熱度 419

在C#中管理Windows服務(安裝、啟動、停止、卸載)需要使用System.ServiceProcess命名空間以及可能的進程調用(如sc.exe)。以下代碼示例分為兩部分:將程序安裝為服務停止/卸載服務。

1、將程序安裝為Windows服務

2、停止并卸載Windows服務

前提條件:目標程序必須實現Windows服務邏輯(如繼承自ServiceBase的.NET程序或符合Windows服務標準的可執行文件)。

public class exeSysService

{

    // 使用sc.exe安裝服務

    public static void InstallService(string serviceName, string executablePath)

    {

        Process process = new Process();

        ProcessStartInfo startInfo = new ProcessStartInfo

        {

            FileName = "sc.exe",

            Arguments = $"create \"{serviceName}\" binPath= \"{executablePath}\" start= auto",

            WindowStyle = ProcessWindowStyle.Hidden,

            Verb = "runas" // 請求管理員權限

        };

        process.StartInfo = startInfo;

        process.Start();

        process.WaitForExit();


        if (process.ExitCode == 0)

        {

            Console.WriteLine("服務安裝成功!");

            StartService(serviceName); // 安裝后啟動服務

        }

        else

        {

            Console.WriteLine($"服務安裝失敗,錯誤代碼: {process.ExitCode}");

        }

    }


    // 啟動服務

    private static void StartService(string serviceName)

    {

        using (ServiceController service = new ServiceController(serviceName))

        {

            if (service.Status != ServiceControllerStatus.Running)

            {

                service.Start();

                service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(30));

                Console.WriteLine("服務已啟動!");

            }

        }

    }



    // 停止并卸載服務

    public static void UninstallService(string serviceName)

    {

        StopService(serviceName); // 先停止服務


        Process process = new Process();

        ProcessStartInfo startInfo = new ProcessStartInfo

        {

            FileName = "sc.exe",

            Arguments = $"delete \"{serviceName}\"",

            WindowStyle = ProcessWindowStyle.Hidden,

            Verb = "runas" // 請求管理員權限

        };

        process.StartInfo = startInfo;

        process.Start();

        process.WaitForExit();


        if (process.ExitCode == 0)

            Console.WriteLine("服務卸載成功!");

        else

            Console.WriteLine($"服務卸載失敗,錯誤代碼: {process.ExitCode}");

    }


    // 停止服務

    private static void StopService(string serviceName)

    {

        using (ServiceController service = new ServiceController(serviceName))

        {

            if (service.CanStop && service.Status != ServiceControllerStatus.Stopped)

            {

                service.Stop();

                service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(30));

                Console.WriteLine("服務已停止!");

            }

        }

    }

}

使用示例

// 安裝服務

ServiceInstaller.InstallService(

    "MyService",          // 服務名稱

    @"C:\MyApp\MyService.exe" // 可執行文件路徑

);


// 卸載服務

ServiceUninstaller.UninstallService("MyService");

關鍵注意事項

1、管理員權限:操作服務需要以管理員身份運行程序(在Visual Studio中右鍵項目 → 屬性 → 安全性 → 勾選“啟用ClickOnce安全設置”,或在清單文件中設置requestedExecutionLevel level="requireAdministrator")。

2、服務程序要求

  • 目標程序必須是專門設計的Windows服務(如.NET中繼承ServiceBase)。

  • 普通.exe程序無法直接作為服務安裝(需使用NSSM等工具封裝)。

3、錯誤處理:添加更完善的異常處理(如服務不存在時的InvalidOperationException)。

4、超時處理WaitForStatus可能因服務未及時響應而超時,需額外處理。

替代方案:使用Windows API

更高級的場景可調用Windows API(如CreateServiceOpenSCManager),需通過P/Invoke調用advapi32.dll,代碼復雜度較高。推薦使用上述sc.exe方案或開源庫(如Topshelf)簡化開發。

在 C# 中判斷 Windows 服務是否已安裝,可以通過 ServiceController 類來實現。以下是完整的代碼示例:

using System;

using System.ServiceProcess;

using System.Collections.Generic;


public class ServiceHelper

{

    /// <summary>

    /// 檢查服務是否已安裝

    /// </summary>

    /// <param name="serviceName">服務名稱</param>

    /// <returns>true 表示已安裝,false 表示未安裝</returns>

    public static bool IsServiceInstalled(string serviceName)

    {

        try

        {

            // 獲取所有服務

            ServiceController[] services = ServiceController.GetServices();

            

            // 遍歷檢查服務是否存在

            foreach (ServiceController service in services)

            {

                if (service.ServiceName.Equals(serviceName, StringComparison.OrdinalIgnoreCase))

                {

                    return true;

                }

            }

            return false;

        }

        catch (Exception ex)

        {

            Console.WriteLine($"檢查服務時出錯: {ex.Message}");

            return false;

        }

    }


    /// <summary>

    /// 檢查服務是否已安裝(使用 LINQ 優化版本)

    /// </summary>

    public static bool IsServiceInstalledLinq(string serviceName)

    {

        try

        {

            return Array.Exists(ServiceController.GetServices(), 

                service => service.ServiceName.Equals(serviceName, StringComparison.OrdinalIgnoreCase));

        }

        catch (Exception ex)

        {

            Console.WriteLine($"檢查服務時出錯: {ex.Message}");

            return false;

        }

    }


    /// <summary>

    /// 獲取所有已安裝服務的名稱列表

    /// </summary>

    public static List<string> GetAllInstalledServices()

    {

        List<string> serviceNames = new List<string>();

        try

        {

            foreach (ServiceController service in ServiceController.GetServices())

            {

                serviceNames.Add(service.ServiceName);

            }

        }

        catch (Exception ex)

        {

            Console.WriteLine($"獲取服務列表時出錯: {ex.Message}");

        }

        return serviceNames;

    }

}


// 使用示例

class Program

{

    static void Main(string[] args)

    {

        string serviceName = "Winmgmt"; // Windows 管理規范服務(通常存在的服務)

        

        // 檢查服務是否安裝

        bool isInstalled = ServiceHelper.IsServiceInstalled(serviceName);

        Console.WriteLine($"服務 '{serviceName}' 是否已安裝: {isInstalled}");

        

        // 檢查不存在的服務

        string nonExisting = "MyFakeService123";

        bool notInstalled = ServiceHelper.IsServiceInstalled(nonExisting);

        Console.WriteLine($"服務 '{nonExisting}' 是否已安裝: {notInstalled}");

        

        // 獲取所有服務(僅顯示前10個)

        Console.WriteLine("\n已安裝服務列表(前10個):");

        var services = ServiceHelper.GetAllInstalledServices();

        foreach (string name in services.Take(10))

        {

            Console.WriteLine($"- {name}");

        }

    }

}

關鍵說明:

1、核心方法

ServiceController.GetServices()

這個方法返回本地計算機上所有 Windows 服務的數組。

2、檢查服務是否存在

Array.Exists(services, s => s.ServiceName.Equals(serviceName, StringComparison.OrdinalIgnoreCase));

使用 Array.Exists 配合不區分大小寫的比較來檢查服務是否存在

3、錯誤處理

  • 方法包含 try-catch 塊處理可能的異常(如訪問權限不足)

  • 當服務控制管理器不可訪問時返回 false

4、注意事項

  • 需要 System.ServiceProcess 程序集引用

  • 應用程序可能需要以管理員權限運行才能訪問某些服務信息

  • 服務名稱是系統內部名稱(如 "wuauserv"),不是顯示名稱(如 "Windows Update")

使用場景示例:

// 在安裝服務前檢查是否已存在

string myService = "MyCustomService";

if (ServiceHelper.IsServiceInstalled(myService))

{

    Console.WriteLine("服務已存在,跳過安裝");

}

else

{

    Console.WriteLine("服務未安裝,執行安裝操作");

    // 這里調用服務安裝邏輯

}


// 在卸載服務前確認存在

if (ServiceHelper.IsServiceInstalled(myService))

{

    Console.WriteLine("服務存在,執行卸載");

    // 這里調用服務卸載邏輯

}

else

{

    Console.WriteLine("服務不存在,無需卸載");

}

性能考慮:

對于需要頻繁檢查服務狀態的場景,建議緩存服務列表:

private static ServiceController[] _cachedServices;

private static DateTime _lastRefresh = DateTime.MinValue;


public static bool IsServiceInstalledCached(string serviceName, bool forceRefresh = false)

{

    try

    {

        // 每5分鐘刷新一次緩存

        if (forceRefresh || _cachedServices == null || (DateTime.Now - _lastRefresh).TotalMinutes > 5)

        {

            _cachedServices = ServiceController.GetServices();

            _lastRefresh = DateTime.Now;

        }

        

        return Array.Exists(_cachedServices, 

            service => service.ServiceName.Equals(serviceName, StringComparison.OrdinalIgnoreCase));

    }

    catch (Exception ex)

    {

        Console.WriteLine($"檢查服務時出錯: {ex.Message}");

        return false;

    }

}

這種方法可以顯著提高頻繁調用的性能,同時保持數據的相對新鮮度。


該文章在 2025/6/2 18:52:24 編輯過
關鍵字查詢
相關文章
正在查詢...
點晴ERP是一款針對中小制造業的專業生產管理軟件系統,系統成熟度和易用性得到了國內大量中小企業的青睞。
點晴PMS碼頭管理系統主要針對港口碼頭集裝箱與散貨日常運作、調度、堆場、車隊、財務費用、相關報表等業務管理,結合碼頭的業務特點,圍繞調度、堆場作業而開發的。集技術的先進性、管理的有效性于一體,是物流碼頭及其他港口類企業的高效ERP管理信息系統。
點晴WMS倉儲管理系統提供了貨物產品管理,銷售管理,采購管理,倉儲管理,倉庫管理,保質期管理,貨位管理,庫位管理,生產管理,WMS管理系統,標簽打印,條形碼,二維碼管理,批號管理軟件。
點晴免費OA是一款軟件和通用服務都免費,不限功能、不限時間、不限用戶的免費OA協同辦公管理系統。
Copyright 2010-2025 ClickSun All Rights Reserved

主站蜘蛛池模板: 国产欧美日韩第一页 | 国产一区二区xxx | 国产激情在线五月天 | 老汉色影院首页 | 国产性爱专区在线 | 露脸国产 | 丝袜美腿女邻居人 | 精品免费视在线观看 | 国产美女裸网站 | 国产高清视频欧美 | 国语自产精品视频 | 成人二区| 波多野结衣福利在线 | 三极国产精品 | 91精品一区福利 | 精品影视综合国产 | 欧洲无线乱| 精品潘金莲 | 日韩免费在线观看 | 91最新九颜色精品 | 区二区在线播放 | 97免费观看视频 | 国产伦精| 97青草最新免费 | 欧美日韩亚洲第一页 | 69精品人人槡 | 91免费视频在线 | 国产精品秘在线观看 | 午夜免费日韩小电影 | 日韩中文高清一 | 日韩在线观看免费 | 国产精品午夜视频 | 九九热国产视频精品 | 国产爽片 | 日本高清一区二区 | 国产在线观看福利片 | 精品自拍视频曝光 | 三年中文在线观看免 | 精品91人人 | 国产区日韩区欧美区 | 国产999免|