升級程序爲獨立的exe程序,由客戶端程序調用實現。
客戶端調用部分
/* 客戶端代碼中,調用更新程序部分 */
static bool CheckUpdate()
{
try
{
//string tmpFileName = System.IO.Directory.GetCurrentDirectory() + "\\" + "Update.exe";
//Process p = Process.Start(tmpFileName, (CommonSetting.SchoolCode + "+" + CommonSetting.SchoolPassword + "+" + CommonSetting.Url));
//p.WaitForExit();
//啓動客戶端升級程序
string tmpFileName = System.IO.Directory.GetCurrentDirectory() + "\\" + "xxx客戶端升級程序.exe";
string argu1 = "\"" + CommonSetting.SchoolCode + "\""; //向exe傳遞的參數1
string argu2 = "\"" + CommonSetting.SchoolPassword + "\""; //向exe傳遞的參數2
string argu3 = "\"" + CommonSetting.Url + "\""; //向exe傳遞的參數3
Process p = new Process();
p.StartInfo.FileName = tmpFileName;
p.StartInfo.Arguments = argu1 + " " + argu2 + " " + argu3; //構造傳遞的入參
//p.StartInfo.Verb = "RunAs"; //使用管理員權限調用(只在xp系統下有效)
p.Start();
p.WaitForExit(); //等待exe程序執行結束
int exCode = p.ExitCode; //獲取exe的返回值
if (exCode == -1)
{
return false;
}
return true;
}
catch (Exception)
{
//MessageBox.Show("更新失敗!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
更新程序部分
/* 更新程序部分 */
static int Main(string[] args)
{
bool flagAdmin = IsAdministrator(); //獲取Windows系統管理員權限(下載文件到C盤)
if (!flagAdmin)
{
MessageBox.Show("xxx升級程序無法獲取系統管理員權限!", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
return -1;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (args.Length != 3) //校驗參數個數
{
return -1;
}
//MessageBox.Show("args length: " + args.Length.ToString());
//for(int i=0; i<args.Length; i++)
//{
// MessageBox.Show(args[i]);
//}
string schoolID = args[0]; //獲取參數1
string linkCode = args[1]; //獲取參數2
string yjServerURL = args[2]; //獲取參數3
//啓動升級程序主界面
//......
flagAdmin = false;
return 0;
}
判斷程序的運行是否有Windows系統管理員權限
/* 判斷當前是否具有管理員權限 */
public static bool IsAdministrator()
{
WindowsIdentity current = WindowsIdentity.GetCurrent();
WindowsPrincipal windowsPrincipal = new WindowsPrincipal(current);
bool flag = windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
return flag;
}
修改.NET程序的運行權限
在工程中Properties中app.manifest文件中修改下圖紅色區域部分level字段的值,可修改爲下圖藍色框中的值。
其中,asInvoker爲普通用戶權限;requireAdministrator詢問客戶是否給予程序管理員權限,大部分軟件採用此種方式;highestAvailable賦予程序超級管理員權限。
注意:當軟件存在獲取管理員權限操作時,裝有“安全衛士”等防護軟件的電腦上有可能會頭彈窗提示不安全,選擇“允許訪問”即可。