ConsoleFunction - Tools.cs 2.19 KB
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

using Microsoft.Web.Administration;
using System.Management;
using System.Diagnostics;

using Vrh.XmlProcessing;
using System.Xml.Linq;

namespace Vrh.Log4Pro.MaintenanceConsole
{
	public static class Tools 
	{
		public static bool IsElevated
		{
			get
			{
				return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
			}
		}
		public static string ExecuteAndGetStdIo(string exepath, string args)
		{
			StringBuilder outputBuilder = new StringBuilder();
			StringBuilder erroroutputBuilder = new StringBuilder();
			ProcessStartInfo startInfo = new ProcessStartInfo() { };
			using (Process exeProcess = new Process())
			{
				startInfo.CreateNoWindow = true;
				startInfo.WindowStyle = ProcessWindowStyle.Hidden;
				startInfo.RedirectStandardOutput = true;
				startInfo.RedirectStandardError= true;
				startInfo.RedirectStandardInput = true;
				startInfo.UseShellExecute = false;
				startInfo.FileName = exepath;
				startInfo.Verb= "runas";
				startInfo.Arguments = args;

				exeProcess.StartInfo = startInfo;
				// enable raising events because Process does not raise events by default
				exeProcess.EnableRaisingEvents = true;
				exeProcess.OutputDataReceived += new DataReceivedEventHandler
				(
					delegate (object sender, DataReceivedEventArgs e)
					{
						// append the new data to the data already read-in
						outputBuilder.Append(e.Data + "\r\n");
					}
				);
				exeProcess.ErrorDataReceived += new DataReceivedEventHandler
				(
					delegate (object sender, DataReceivedEventArgs e)
					{
						// append the new data to the data already read-in
						erroroutputBuilder.Append(e.Data + "\r\n");
					}
				);
				// start the process
				// then begin asynchronously reading the output
				// then wait for the process to exit
				// then cancel asynchronously reading the output
				exeProcess.Start();
				exeProcess.BeginOutputReadLine();
				exeProcess.WaitForExit();
				exeProcess.CancelOutputRead();
				return outputBuilder.ToString();
			}
		}
	}
}