[Winform] installed on the C drive, a workaround for no operational permissions

Source: Internet
Author: User

Summary

When WinForm is packaged and installed, the default installation path is generally used, which is installed by default in the C:\Program files\xx or C:\Program Files (x86) directory, but Windows has a security policy The default is not to allow the operation of C-disk files or folders.

Solutions

In the software release, the software EXE will generally be signed, so that its publishers display as XXX company, it is recommended to build another software startup program to sign the startup program. This way, if your software is updated, you do not need to sign the software repeatedly.

1, start the program can, in the configuration file, set the name of the startup EXE. One startup program can be common to multiple software, and changing the startup program name has no effect on signing.

2. You can verify the permissions of the software catalog in the startup program. If you do not have permissions, you can let it pop up the UAC window, run as an administrator, and in the main program, authorize the directory where the software resides.

Core code

Start the program

  classProgram {Static string_exename = configurationmanager.appsettings["exename"]; Static string_exedir =AppDomain.CurrentDomain.BaseDirectory; Static string_startexepath =Path.Combine (_exedir, _exename); StaticEventLog log =NewEventLog () {Source =path.getfilenamewithoutextension (_exename)}; Static voidMain (string[] args) {            Try            {                if(string. IsNullOrEmpty (_exename)) {log. WriteEntry ("no set exe name", EventLogEntryType.Error); }                Else                {                    if(!ISAdmin ()) {                        //do you have Full Control permissions                        if(Checkfolderpermissions (_exedir, Filesystemrights.fullcontrol)) { /c8>//run the main process without popping the UAC windowRunAsAdmin (false); }                        Else                        {                            //pops up the UAC window, runs the program as an administrator, and makes folder authorization in the main programRunAsAdmin (true); }                    }                    Else                    {                        //run the main process without popping the UAC windowRunAsAdmin (false); }                }            }            Catch(Exception ex) {log. WriteEntry (ex.            Message, EventLogEntryType.Error); }        }        /// <summary>        ///Check folder permissions/// </summary>        /// <param name= "Dirpath" ></param>        /// <param name= "AccessType" ></param>        /// <returns></returns>         Public Static BOOLCheckfolderpermissions (stringDirpath, Filesystemrights accessType) {            BOOLHavepermission =true; Try{authorizationrulecollection Collection=Directory. GetAccessControl (Dirpath). Getaccessrules (true,true,typeof(System.Security.Principal.NTAccount)); foreach(FileSystemAccessRule ruleinchcollection) {                    if(rule. Filesystemrights & AccessType) >0)                    {                        returnhavepermission; }                }            }            Catch{havepermission=false; }            returnhavepermission; }        /// <summary>        ///Run as administrator, pop up the UAC control window/// </summary>        /// <param name= "Isrunasadmin" >whether to eject UAC control</param>        Private Static voidRunAsAdmin (BOOLisrunasadmin) {            //To Create a startup objectSystem.Diagnostics.ProcessStartInfo StartInfo =NewSystem.Diagnostics.ProcessStartInfo (); //set up a run fileStartinfo.filename =_startexepath; if(isrunasadmin) {//set the start action to ensure that you are running as an administratorStartinfo.verb ="runas"; }            if(File.exists (_startexepath)) {//if it is not an administrator, start UACSystem.Diagnostics.Process.Start (startinfo); }            Else{log. WriteEntry ("Not find the appication to run", EventLogEntryType.Error); }        }        /// <summary>        ///whether it is an administrator/// </summary>        /// <returns></returns>        Static BOOLISAdmin () {Try{System.Security.Principal.WindowsIdentity Identity=System.Security.Principal.WindowsIdentity.GetCurrent (); System.Security.Principal.WindowsPrincipal Principal=NewSystem.Security.Principal.WindowsPrincipal (identity); returnprincipal.            IsInRole (System.Security.Principal.WindowsBuiltInRole.Administrator); }            Catch            {                return false; }        }    }

The main program is authorized in the main function

Setaccess ("Users", Staticparameter.exedir);
        /// <summary>        ///Specify full access permissions for the specified user group, authorized directory/// </summary>        /// <param name= "user" >user groups, such as users</param>        /// <param name= "folder" >the actual directory</param>        /// <returns></returns>         Public Static BOOLSetaccess (stringUserstringfolder) {            //permissions defined as Full Control            ConstFilesystemrights rights =Filesystemrights.fullcontrol; //add access rules to the actual directory            varAccessrule =NewFileSystemAccessRule (user, rights, Inheritanceflags.none, Propagationflags.nopropagate            Inherit, Accesscontroltype.allow); varInfo =NewDirectoryInfo (folder); varSecurity =Info.getaccesscontrol (accesscontrolsections.access); BOOLResult; Security.modifyaccessrule (Accesscontrolmodification.set, Accessrule, outResult); if(! Result)return false; //object inheritance is always allowed on re-directories            ConstInheritanceFlags iflags = Inheritanceflags.containerinherit |Inheritanceflags.objectinherit; //Add an access rule for an inheritance relationshipAccessrule =NewFileSystemAccessRule (user, rights, IFlags, Propagationflags.inheritonly,            Accesscontroltype.allow); Security.modifyaccessrule (Accesscontrolmodification.add, Accessrule, outResult); if(! Result)return false;            Info.setaccesscontrol (Security); return true; }

At the time of authorization, you need to ensure that the administrator is running. In the startup program, you can determine the permissions of the directory, if not authorized, then pop up the UAC window to run as an administrator, first run authorization, and then run to skip the process.

Summarize

File and folder right, in C/S is a frequently encountered problem. For example, if you do not have read and write permissions, if you operate SQLite will prompt you do not have permission to operate the database bug.

Reference

Http://www.cnblogs.com/wuhuacong/p/5645172.html

[Winform] installed on the C drive, a workaround for no operational permissions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.