LOGO OA教程 ERP教程 模切知識交流 PMS教程 CRM教程 開發(fā)文檔 其他文檔  
 
網(wǎng)站管理員

C# 設(shè)置指定程序為Windows系統(tǒng)服務(wù)方式運行,或者關(guān)閉指定程序在Windows系統(tǒng)服務(wù)

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

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

1、將程序安裝為Windows服務(wù)

2、停止并卸載Windows服務(wù)

前提條件:目標(biāo)程序必須實現(xiàn)Windows服務(wù)邏輯(如繼承自ServiceBase的.NET程序或符合Windows服務(wù)標(biāo)準(zhǔn)的可執(zhí)行文件)。

public class exeSysService

{

    // 使用sc.exe安裝服務(wù)

    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" // 請求管理員權(quán)限

        };

        process.StartInfo = startInfo;

        process.Start();

        process.WaitForExit();


        if (process.ExitCode == 0)

        {

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

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

        }

        else

        {

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

        }

    }


    // 啟動服務(wù)

    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("服務(wù)已啟動!");

            }

        }

    }



    // 停止并卸載服務(wù)

    public static void UninstallService(string serviceName)

    {

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


        Process process = new Process();

        ProcessStartInfo startInfo = new ProcessStartInfo

        {

            FileName = "sc.exe",

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

            WindowStyle = ProcessWindowStyle.Hidden,

            Verb = "runas" // 請求管理員權(quán)限

        };

        process.StartInfo = startInfo;

        process.Start();

        process.WaitForExit();


        if (process.ExitCode == 0)

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

        else

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

    }


    // 停止服務(wù)

    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("服務(wù)已停止!");

            }

        }

    }

}

使用示例

// 安裝服務(wù)

ServiceInstaller.InstallService(

    "MyService",          // 服務(wù)名稱

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

);


// 卸載服務(wù)

ServiceUninstaller.UninstallService("MyService");

關(guān)鍵注意事項

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

2、服務(wù)程序要求

  • 目標(biāo)程序必須是專門設(shè)計的Windows服務(wù)(如.NET中繼承ServiceBase)。

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

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

4、超時處理WaitForStatus可能因服務(wù)未及時響應(yīng)而超時,需額外處理。

替代方案:使用Windows API

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

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

using System;

using System.ServiceProcess;

using System.Collections.Generic;


public class ServiceHelper

{

    /// <summary>

    /// 檢查服務(wù)是否已安裝

    /// </summary>

    /// <param name="serviceName">服務(wù)名稱</param>

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

    public static bool IsServiceInstalled(string serviceName)

    {

        try

        {

            // 獲取所有服務(wù)

            ServiceController[] services = ServiceController.GetServices();

            

            // 遍歷檢查服務(wù)是否存在

            foreach (ServiceController service in services)

            {

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

                {

                    return true;

                }

            }

            return false;

        }

        catch (Exception ex)

        {

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

            return false;

        }

    }


    /// <summary>

    /// 檢查服務(wù)是否已安裝(使用 LINQ 優(yōu)化版本)

    /// </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($"檢查服務(wù)時出錯: {ex.Message}");

            return false;

        }

    }


    /// <summary>

    /// 獲取所有已安裝服務(wù)的名稱列表

    /// </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($"獲取服務(wù)列表時出錯: {ex.Message}");

        }

        return serviceNames;

    }

}


// 使用示例

class Program

{

    static void Main(string[] args)

    {

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

        

        // 檢查服務(wù)是否安裝

        bool isInstalled = ServiceHelper.IsServiceInstalled(serviceName);

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

        

        // 檢查不存在的服務(wù)

        string nonExisting = "MyFakeService123";

        bool notInstalled = ServiceHelper.IsServiceInstalled(nonExisting);

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

        

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

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

        var services = ServiceHelper.GetAllInstalledServices();

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

        {

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

        }

    }

}

關(guān)鍵說明:

1、核心方法

ServiceController.GetServices()

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

2、檢查服務(wù)是否存在

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

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

3、錯誤處理

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

  • 當(dāng)服務(wù)控制管理器不可訪問時返回 false

4、注意事項

  • 需要 System.ServiceProcess 程序集引用

  • 應(yīng)用程序可能需要以管理員權(quán)限運行才能訪問某些服務(wù)信息

  • 服務(wù)名稱是系統(tǒng)內(nèi)部名稱(如 "wuauserv"),不是顯示名稱(如 "Windows Update")

使用場景示例:

// 在安裝服務(wù)前檢查是否已存在

string myService = "MyCustomService";

if (ServiceHelper.IsServiceInstalled(myService))

{

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

}

else

{

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

    // 這里調(diào)用服務(wù)安裝邏輯

}


// 在卸載服務(wù)前確認(rèn)存在

if (ServiceHelper.IsServiceInstalled(myService))

{

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

    // 這里調(diào)用服務(wù)卸載邏輯

}

else

{

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

}

性能考慮:

對于需要頻繁檢查服務(wù)狀態(tài)的場景,建議緩存服務(wù)列表:

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($"檢查服務(wù)時出錯: {ex.Message}");

        return false;

    }

}

這種方法可以顯著提高頻繁調(diào)用的性能,同時保持?jǐn)?shù)據(jù)的相對新鮮度。


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

黄频国产免费高清视频,久久不卡精品中文字幕一区,激情五月天AV电影在线观看,欧美国产韩国日本一区二区
在线观看肉片AV网站免费 | 中文字幕一二区二三区 | 亚洲国产精品久久三级视频 | 天天综合网久久综合免费成人 | 午夜男女爽爽视频在线观看 | 久草视频免费在线观看 |