1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C#管理者実行

Posted at
runadmin.cs

using System; 
using System.IO;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Windows.Forms;

public class RunAdmin
{
	//ハッシュ取得用メソッド
	static string gethash(string strFilePath){

		var fs = new FileStream(strFilePath, FileMode.Open, FileAccess.Read);

		byte[] sha1byte = SHA1.Create().ComputeHash(fs);

		string sha1string = BitConverter.ToString(sha1byte).Replace("-","").ToUpper();

		return sha1string;

	}


	public static void Main(string[] args)
	{

		//自プログラムフォルダパス取得
		string ExePath = System.Reflection.Assembly.GetEntryAssembly().Location;

		//自プログラムフォルダ取得
		string ExeDir = Path.GetDirectoryName(ExePath);

		//対象プログラム
		string TargetExe = "TestApp.exe";

		//対象プログラムハッシュ
		string TargetHash = "B20ECB788F4AAA98A62C5AE334B3C4EE6A26D013";

		//string TargetArguments = "";
	
		

		//引数なし(初回起動時)
		if ( args.Length == 0 ){

			Process p1 = new Process();		

			//別ユーザーとして自プログラムを実行
			p1.StartInfo.FileName = ExePath;
			p1.StartInfo.Arguments = "/runadmin";
			//p.StartInfo.UserName = ""
			//p.StartInfo.Domain = ""
			//p.StartInfo.Password = ""
			p1.StartInfo.UseShellExecute = false;

			p1.Start();
			p1.WaitForExit();

		//引数runadmin指定(2回目起動時)
		} else if( args[0] == "/runadmin" ) {

			string hashresult = gethash(Path.Combine(ExeDir,TargetExe));

			if ( hashresult == TargetHash){

				Process p2 = new Process();

				//別ユーザーとして起動されたので、対象のプログラムを管理者権限で実行
				//対象のファイルのファイルハッシュチェック
				//自分の実行フォルダパス

				p2.StartInfo.FileName = TargetExe;
				p2.StartInfo.UseShellExecute = true;
				p2.StartInfo.Verb = "RunAs";

				//引数が必要な場合に使用
				//p.StartInfo.Arguments = TargetArguments;
				
				p2.Start();
				p2.WaitForExit();

			}else{

				//ハッシュが登録ずみでない
				MessageBox.Show("ファイルハッシュが一致しません");

			}
		} 
	}
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?