C#判断是否是以管理员权限允许当前应用

private static bool CheckForAdminRights()
		{
			string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), string.Format("tfadxp{0}.txt", "80"));
			try
			{
				if (File.Exists(path))
				{
					File.Delete(path);
				}
				using (StreamWriter streamWriter = File.CreateText(path))
				{
					streamWriter.WriteLine("test successful - {0}", DateTime.Now);
					streamWriter.Close();
				}
				if (!File.Exists(path))
				{
					return AdminRightsError();
				}
				File.Delete(path);
			}
			catch (Exception)
			{
				return AdminRightsError();
			}
			return true;
		}

		private static bool AdminRightsError()
		{
			MessageBox.Show("I can not continue, You should run me with administrative priveleges.\n\nRight click on me and select \"Run as administrator\" menu.", "You are NOT ADMINISTRATOR!", MessageBoxButtons.OK, MessageBoxIcon.Hand);
			return false;
		}
posted @ 2020-01-20 18:31  星空天宇  阅读(184)  评论(0编辑  收藏  举报