因為一個比較特殊的原因,需要通過網頁重啟伺服器端的一個程式,也就是先Kill掉,再重新Start,因為asp.net使用者的許可權不夠,如果直接Kill掉進程的話就會錯誤,在網上查了一下也找到比較好的解決方案,於是用了一個很笨的方法:
先寫了一個服務程式,功能是沒隔一秒就檢查一下一個檔案中的內容,如果是wait就什麼都不做,如果是Restart就重啟那個進程。寫好服務程式後安裝到系統上就可以了。
//Program.cs
using System;
using System.Collections.Generic;
using System.ServiceProcess;
using System.Text;
namespace CHED
{
static class Program
{
/// <summary>
/// 應用程式的主進入點。
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Restart_Serv_U()
};
ServiceBase.Run(ServicesToRun);
}
}
}
//Restart_Serv_U.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using Microsoft.Win32;
using System.IO;
using System.Threading;
using System.Windows.Forms;
namespace CHED
{
public partial class Restart_Serv_U : ServiceBase
{
public Restart_Serv_U()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
Thread CHEDThread = new Thread(ServerStart);
CHEDThread.Start();
}
protected override void OnStop()
{
}
private void ServerStart()
{
CHED LCYSC = new CHED();
Application.Run(LCYSC);
}
}
}
//Restart_Serv_U.Designer.cs
namespace CHED
{
partial class Restart_Serv_U
{
/// <summary>
/// 必需的設計器變數。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的資源。
/// </summary>
/// <param name="disposing">如果應釋放託管資源,為 true;否則為 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region 組件設計器產生的程式碼
/// <summary>
/// 設計器支援所需的方法 - 不要
/// 使用代碼編輯器修改此方法的內容。
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.ServiceName = "Service1";
}
#endregion
}
}
//CHED.cs
using System;
using System.Windows.Forms;
using System.Threading;
using Microsoft.Win32;
using System.IO;
namespace CHED
{
public partial class CHED : ApplicationContext
{
public CHED()
{
watcher = new System.Threading.Timer(new TimerCallback(watcherCallBack), null, 1000, 1000);
}
private System.Threading.Timer watcher;
private void watcherCallBack(object o)
{
try
{
string text = File.ReadAllText(@"D:/webroot/CEDC/Manage/Admin/CHED/reset.ched");
if (text == "restart")
{
System.Diagnostics.Process[] pros = System.Diagnostics.Process.GetProcessesByName("Serv-U");
if (pros.Length > 0)
pros[0].Kill();
File.WriteAllText(@"D:/webroot/CEDC/Manage/Admin/CHED/reset.ched", "wait");
}
}
catch { }
}
}
}
還要添加對System.Windows.Forms的引用。
最後在網頁的按鈕事件中把那個檔案的內容寫為restart就可以了。
當然,用同樣的方法可以實現結束其他多個進程,比如在文本中寫入要結束的進程名,當伺服器端的服務程式發現後就把那個進程給kill掉。