程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#版Windows辦事裝置卸載小對象

C#版Windows辦事裝置卸載小對象

編輯:C#入門知識

C#版Windows辦事裝置卸載小對象。本站提示廣大學習愛好者:(C#版Windows辦事裝置卸載小對象)文章只能為提供參考,不一定能成為您想要的結果。以下是C#版Windows辦事裝置卸載小對象正文


媒介
 在我們的任務中,常常碰到Windows辦事的裝置和卸載,在之前公司也普寫過一個WinForm法式選擇裝置途徑,此次再來個玲珑靈巧的掌握台法式,不消再選擇,只需放到須要裝置辦事的目次中運轉便可以完成裝置或卸載。 

開辟思緒
1、因為體系的權限限制,在運轉法式時須要以治理員身份運轉
2、由於須要完成裝置和卸載兩個功效,在法式運轉時提醒本次操作是裝置照樣卸載  須要輸出 1 或 2 
3、接上去法式會查找以後目次中的可履行文件並過濾法式自己和有時我們復制出去的帶有vhost的文件,並列出列表讓操作者選擇(普通情形下只要一個)
4、依據用戶所選停止裝置或卸載操作
5、因為能夠反復操作,須要遞歸挪用一下
詳細完成
起首們要操作辦事,須要用  System.ServiceProcess 來封裝完成類 

using System;
using System.Collections;
using System.Configuration.Install;
using System.Linq;
using System.ServiceProcess;

namespace AutoInstallUtil
{
  public class SystemServices
  {
    /// <summary>
    /// 翻開體系辦事
    /// </summary>
    /// <param name="serviceName">體系辦事稱號</param>
    /// <returns></returns>
    public static bool SystemServiceOpen(string serviceName)
    {
      try
      {
        using (var control = new ServiceController(serviceName))
        {
          if (control.Status != ServiceControllerStatus.Running)
          {
            control.Start();
          }
        }
        return true;
      }
      catch
      {
        return false;
      }
    }


    /// <summary>
    /// 封閉體系辦事
    /// </summary>
    /// <param name="serviceName">體系辦事稱號</param>
    /// <returns></returns>
    public static bool SystemServiceClose(string serviceName)
    {
      try
      {
        using (var control = new ServiceController(serviceName))
        {

          if (control.Status == ServiceControllerStatus.Running)
          {
            control.Stop();
          }
        }
        return true;
      }
      catch
      {
        return false;
      }
    }

    /// <summary>
    /// 重啟體系辦事
    /// </summary>
    /// <param name="serviceName">體系辦事稱號</param>
    /// <returns></returns>
    public static bool SystemServiceReStart(string serviceName)
    {
      try
      {
        using (var control = new ServiceController(serviceName))
        {
          if (control.Status == System.ServiceProcess.ServiceControllerStatus.Running)
          {
            control.Continue();
          }
        }
        return true;
      }
      catch
      {
        return false;
      }
    }

    /// <summary>
    /// 前往辦事狀況
    /// </summary>
    /// <param name="serviceName">體系辦事稱號</param>
    /// <returns>1:辦事未運轉 2:辦事正在啟動 3:辦事正在停滯 4:辦事正在運轉 5:辦事行將持續 6:辦事行將暫停 7:辦事已暫停 0:未知狀況</returns>
    public static int GetSystemServiceStatus(string serviceName)
    {
      try
      {
        using (var control = new ServiceController(serviceName))
        {
          return (int)control.Status;
        }
      }
      catch
      {
        return 0;
      }
    }

    /// <summary>
    /// 前往辦事狀況
    /// </summary>
    /// <param name="serviceName">體系辦事稱號</param>
    /// <returns>1:辦事未運轉 2:辦事正在啟動 3:辦事正在停滯 4:辦事正在運轉 5:辦事行將持續 6:辦事行將暫停 7:辦事已暫停 0:未知狀況</returns>
    public static string GetSystemServiceStatusString(string serviceName)
    {
      try
      {
        using (var control = new ServiceController(serviceName))
        {
          var status = string.Empty;
          switch ((int)control.Status)
          {
            case 1:
              status = "辦事未運轉";
              break;
            case 2:
              status = "辦事正在啟動";
              break;
            case 3:
              status = "辦事正在停滯";
              break;
            case 4:
              status = "辦事正在運轉";
              break;
            case 5:
              status = "辦事行將持續";
              break;
            case 6:
              status = "辦事行將暫停";
              break;
            case 7:
              status = "辦事已暫停";
              break;
            case 0:
              status = "未知狀況";
              break;
          }
          return status;
        }
      }
      catch
      {
        return "未知狀況";
      }
    }

    /// <summary>
    /// 裝置辦事
    /// </summary>
    /// <param name="stateSaver"></param>
    /// <param name="filepath"></param>
    public static void InstallService(IDictionary stateSaver, string filepath)
    {
      try
      {
        var myAssemblyInstaller = new AssemblyInstaller
        {
          UseNewContext = true,
          Path = filepath
        };
        myAssemblyInstaller.Install(stateSaver);
        myAssemblyInstaller.Commit(stateSaver);
        myAssemblyInstaller.Dispose();
      }
      catch (Exception ex)
      {
        throw new Exception("installServiceError/n" + ex.Message);
      }
    }

    public static bool ServiceIsExisted(string serviceName)
    {
      ServiceController[] services = ServiceController.GetServices();
      return services.Any(s => s.ServiceName == serviceName);
    }

    /// <summary>
    /// 卸載辦事
    /// </summary>
    /// <param name="filepath">途徑和文件名</param>
    public static void UnInstallService(string filepath)
    {
      try
      {
        //UnInstall Service 
        var myAssemblyInstaller = new AssemblyInstaller
        {
          UseNewContext = true,
          Path = filepath
        };
        myAssemblyInstaller.Uninstall(null);
        myAssemblyInstaller.Dispose();
      }
      catch (Exception ex)
      {
        throw new Exception("unInstallServiceError/n" + ex.Message);
      }
    }
  }
} 

接上去我們封裝掌握台的操作辦法為了完成輪回監聽這裡用了遞歸 

using System;
using System.Diagnostics;
using System.IO;
using System.Linq;

namespace AutoInstallUtil
{
  class Program
  {
    static void Main(string[] args)
    {
      try
      {
        ServerAction();
      }
      catch (Exception ex)
      {
        Console.WriteLine("產生毛病:{0}", ex.Message);
      }

      Console.ReadKey();
    }

    /// <summary>
    /// 操作
    /// </summary>
    private static void ServerAction()
    {
      Console.WriteLine("請輸出:1裝置 2卸載");
      var condition = Console.ReadLine();
      var currentPath = Environment.CurrentDirectory;
      var currentFileNameVshost = Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName).ToLower();
      var currentFileName = currentFileNameVshost.WordStr(".vshost.exe", ".exe");
      var files =
        Directory.GetFiles(currentPath)
          .Select(o => Path.GetFileName(o).ToLower())
          .ToList()
          .Where(
            o =>
              o != currentFileNameVshost
              && o != currentFileName
              && o.ToLower().EndsWith(".exe")
              && o != "installutil.exe"
              && !o.ToLower().EndsWith(".vshost.exe"))
          .ToList();
      if (files.Count == 0)
      {
        Console.WriteLine("未找到可履行文件,請確認以後目次有須要裝置的辦事法式");
      }
      else
      {
        Console.WriteLine("找到目次有以下可履行文件,請選擇須要裝置或卸載的文件序號:");
      }
      int i = 0;
      foreach (var file in files)
      {
        Console.WriteLine("序號:{0} 文件名:{1}", i, file);
        i++;
      }
      var serviceFileIndex = Console.ReadLine();
      var servicePathName = currentPath + "\\" + files[Convert.ToInt32(serviceFileIndex)];
      if (condition == "1")
      {
        SystemServices.InstallService(null, servicePathName);
      }
      else
      {
        SystemServices.UnInstallService(servicePathName);
      }
      Console.WriteLine("**********本次操作終了**********");
      ServerAction();
    }
  }
}

到此為止簡略的裝置法式就寫完了,為了能干我選了個白色的西紅柿來做為圖標,如許顯示些

源碼和法式:裝置卸載Windows辦事

以上就是本文的全體內容,願望對年夜家的進修有所贊助,也願望年夜家多多支撐。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved