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

Source: Internet
Author: User
Tags sqlite database

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 of the application. //        </summary>        [STAThread]        private static void 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>///For the specified user group, the authorized directory specifies full access rights//</summary>//<param name= "user" User groups, such as users</param>//<param name= "folder" > actual directory </param>///<returns></returns > private static bool Setaccess (string user, String folder) {//defined as Full Control permissions Const FI            lesystemrights rights = Filesystemrights.fullcontrol;                Add access rules to the actual directory var accessrule = new FileSystemAccessRule (user, rights, Inheritanceflags.none,            Propagationflags.nopropagateinherit, Accesscontroltype.allow);            var Info = new DirectoryInfo (folder);            var Security = Info.getaccesscontrol (accesscontrolsections.access);            BOOL Result;            Security.modifyaccessrule (Accesscontrolmodification.set, Accessrule, out Result); if (!            Result) return false; Always allow object inheritance on re-directories const inheritanceflags IFLAGS = INHEritanceflags.containerinherit |            Inheritanceflags.objectinherit; Add an access rule for an inheritance relationship accessrule = new FileSystemAccessRule (user, rights, IFlags, Propaga            Tionflags.inheritonly, Accesscontroltype.allow);            Security.modifyaccessrule (Accesscontrolmodification.add, Accessrule, out Result); if (!            Result) return false;            Info.setaccesscontrol (Security);        return true; }

Then we can call it in the main function.

<summary>///The main entry point of the application. </summary> [STAThread] private static void Main () {//Specify full access permissions for the user group for the corresponding directorysetaccess ("Users", Application.startuppath); Interface Chinese System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo ("Zh-hans")            ;            DevExpress.UserSkins.BonusSkins.Register ();            DevExpress.Skins.SkinManager.EnableFormSkins ();            Application.enablevisualstyles ();            Application.setcompatibletextrenderingdefault (FALSE);            Application.ThreadException + = new System.Threading.ThreadExceptionEventHandler (application_threadexception);            Login interface Login DLG = new Login (); Dlg.            StartPosition = Formstartposition.centerscreen; if (DialogResult.OK = = dlg. ShowDialog ()) {if (dlg.blogin) {SplashScreen.Splasher.Show (t                    Ypeof (Splashscreen.frmsplash)); Gc.                    Maindialog = new MainForm (); 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.