日记大全

日记大全 > 句子大全

C 向C盘写入文件(解决没有权限 无法写入的问题)

句子大全 2010-11-24 22:00:04
相关推荐

问题现象:C# 向C盘写入文件,但是提示没有权限

问题原因:

最新的win8/win10等操作系统 在向c盘写入文件时 需要管理员权限才能运行

解决方案:

打开软件时即用管理员身份打开,相关代码如下:

/// <summary>/// 应用程序的主入口点。/// </summary>[STAThread]static void Main(string[] Args){//var j = 0;//var i = 100/j;try{//下为: Vista/win7/win8/win10 on up/*** 当前用户是管理员的时候,直接启动应用程序* 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行*///获得当前登录的Windows用户标示System.Security.Principal.WindowsIdentity identity =System.Security.Principal.WindowsIdentity.GetCurrent();//创建Windows用户主题Application.EnableVisualStyles();System.Security.Principal.WindowsPrincipal principal =new System.Security.Principal.WindowsPrincipal(identity);//判断当前登录用户是否为管理员if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator)){//如果是管理员,则直接运行Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);Application.Run(new Test());}else{//创建启动对象System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();//设置运行文件startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;//设置启动参数startInfo.Arguments = String.Join(" ", Args);//设置启动动作,确保以管理员身份运行startInfo.Verb = "runas";//如果不是管理员,则启动UACSystem.Diagnostics.Process.Start(startInfo);//退出System.Windows.Forms.Application.Exit();}}catch (Exception start_ex){//MyLog.Error(start_ex);}}

最终效果:

阅读剩余内容
网友评论
相关内容
拓展阅读
最近更新