Set administrator permissions and add write permissions to user groups in the WinForm program

Source: Internet
Author: User
Tags sqlite database

Original: Set administrator permissions in the WinForm program and add write permissions to the user group

In some of our WinForm programs, often need to have some special permissions to the operating system files, we can set the running program with administrator rights or set the directory to run the program has write permissions, if it is inside the operating system, we can set the running program to run as Administrator, or setting the users user group to have write permissions in the running directory solves the problem, but what if we want to do it automatically with C # code?

1, System settings Administrator rights or directory write permissions

If we need to have the program run as an administrator, you can do so by setting the properties of the shortcut or the application's properties as "Run this program as an administrator", as shown below.

If we need some permission to write files, such as our program may need to manipulate the SQLite file database, you can also set the users user group in the running directory with Write permissions can resolve the problem, or may appear "attempt to write a readonly Database "error.

We set the steps as follows: Locate the folder where the SQLite database resides, right-click, Properties---security, and add write permissions to the users user group.

2, using C # code implementation

The above steps can solve the access problem we actually encountered, so if we use C # code, how should we implement these operations?

For the first process to run a program as an administrator, we can do so by modifying the configuration of the program, which avoids some of the permissions problems of the WinForm program at runtime:

1) When executing the cmd command through the WinForm program, in some cases the command is not valid if it is not running as an administrator.

2) or when you execute the Windows Service service through the WinForm program, you also need to be an administrator to invoke service services.

3) Handle other related actions that require administrator status.

If we are compiling the WinForm program, it takes only a few steps to get the administrator to run the program, as shown below in our WinForm UI Project "Properties", "Security", tick clickone settings.

Then we can see that in the UI project "Properties" directory, a app.manifest file is generated.

This app.manifest file is automatically generated, we modify one of the settings, and then uncheck the above check clickone settings.

Put the contents of the App.manifest file:

<requestedexecutionlevel level= "asInvoker" uiaccess= "false"/>

Switch

<requestedexecutionlevel level= "requireadministrator" uiaccess= "false"/>

Then uncheck the Clickone settings above and recompile the entire program.

When the program runs, it will prompt "user Account Control" to get administrator privileges to run, click "Yes" to get administrator privileges.

You can also work with C # code to set user group permissions for the specified directory.

In general, we can in the program installation or startup, the directory to the user group permissions processing, so that the program runs naturally with the corresponding directory read and write permissions.

If we do this at the start of the program, we can set it in the main function.

        /// <summary>        /// The main entry point for the application.         /// </summary>         [STAThread]        privatestaticvoid  Main ()        {        } 

For ease of handling, we add a public function to handle the directory access operation of the user group, as shown in the C # code below.

        /// <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>        Private 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; }

Then we can call it in the main function.

        /// <summary>        ///The main entry point for the application. /// </summary>[STAThread]Private Static voidMain () {//Specify full access permissions for the user group for the corresponding directorysetaccess ("Users", Application.startuppath); //interface of ChineseSystem.Threading.Thread.CurrentThread.CurrentUICulture =NewSystem.Globalization.CultureInfo ("Zh-hans");            DevExpress.UserSkins.BonusSkins.Register ();            DevExpress.Skins.SkinManager.EnableFormSkins ();            Application.enablevisualstyles (); Application.setcompatibletextrenderingdefault (false); Application.ThreadException+=NewSystem.Threading.ThreadExceptionEventHandler (application_threadexception); //Login InterfaceLogin dlg =NewLogin (); Dlg. StartPosition=Formstartposition.centerscreen; if(DialogResult.OK = =dlg. ShowDialog ()) {if(Dlg.blogin) {SplashScreen.Splasher.Show (typeof(Splashscreen.frmsplash)); Gc. Maindialog=NewMainForm (); Gc. Maindialog.startposition=Formstartposition.centerscreen; Application.Run (GC.                Maindialog); }} dlg.        Dispose (); }

So after the program runs, we can see that the corresponding directory has full access to read and write operations, so for some, such as read and write SQLite error problems, it will be solved.

The above is my two different access to the processing experience summary, I hope to WinForm development in the peer reference, thanks to the patient reading and support.

Set administrator permissions and add write permissions to user groups in the WinForm program

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.