Set administrator permissions in the Winform program and add write permissions to the user group.

Source: Internet
Author: User

Set administrator permissions in the Winform program and add write permissions to the user group.

In some of our Winform programs, we often need some special permissions to operate system files. We can set the running program to have administrator permissions or set the directory of the running program to have write permissions, in the operating system, you can set the running program to run as an administrator, or set the Users user group to have the write permission in the running directory to solve the problem, but if we want to use the C # code for automatic processing, how should we implement it?

1. The system sets administrator or directory write permissions.

If you want to run the program as an administrator, you can set the shortcut attribute or the application attribute to run the program as an administrator, as shown below.

If we need some file write permissions, for example, our program may need to operate the SQLite file database, you can also solve the problem by setting the Users user group to have write permissions in the running directory, otherwise, the [attempt to write a readonly database] error may occur.

The procedure is as follows: Find the folder where the SQLite database is located, right-click, and choose Properties> Security to add write permissions to the Users user group.

 

2. Use C # code for implementation

The above steps solve the actual access permission problem. How should we implement these operations if we use the C # code?

For the first operation to run a program as an administrator, we can modify the configuration of the program to avoid the permission issues during Winform running:

1) when executing the cmd command through the winform program, in some cases, if the command is not run as an administrator, the system will prompt that the command is invalid.

2) When you use the winform program to run the Windows Service, you also need to be an administrator to call the Service.

3) process other operations that require the Administrator identity.

If we compile the Winform program, we only need a few steps to get the Administrator identity when the program is running, as shown below in the Winform UI project [properties] [security, select ClickOne.

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

The app. manifest file is automatically generated. modify one of the settings and deselect the ClickOne setting.

Put the content of the app. manifest file:

<RequestedExecutionLevel level = "asInvoker" uiAccess = "false"/>

Changed:

<RequestedExecutionLevel level = "requireAdministrator" uiAccess = "false"/>

In this way, cancel the ClickOne settings selected above and re-compile the entire program.

When running the program, the system prompts "User Account Control" to get the Administrator permission to run the program. Click "yes" to get the Administrator permission.

 

You can use the C # code to set user group permissions for a specified directory.

In general, we can process user group permissions on directories during program installation or startup, so that the program runs properly and has the read and write permissions on the corresponding directories.

For example, when the program is started, we can set it in the Main function.

/// <Summary> /// main entry point of the application. /// </Summary> [STAThread] private static void Main (){}

To facilitate processing, we add a public function to process the directory access operation of the user group. The C # code is as follows.

/// <Summary> /// specify the full access permission for the authorization directory for the specified user group. /// </summary> /// <param name = "user"> user Group, for example, Users </param> /// <param name = "folder"> actual directory </param> /// <returns> </returns> private static bool SetAccess (string user, string folder) {// defined as the fully-controlled permission const FileSystemRights Rights = FileSystemRights. fullControl; // Add the access rule to the actual directory var AccessRule = new FileSystemAccessRule (user, Rights, InheritanceFlags. none, PropagationFlag S. 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; // It is always allowed to inherit const InheritanceFlags iFlags = InheritanceFlags from the directory. containerInherit | InheritanceFlags. objectInherit; // Add the access rule AccessRule = new FileSystemAccessRule (user, Rights, iFlags, PropagationFlags. inheritOnly, AccessControlType. allow); Security. modifyAccessRule (AccessControlModification. add, AccessRule, out Result); if (! Result) return false; Info. SetAccessControl (Security); return true ;}

Then we can call the Main function.

/// <Summary> /// main entry point of the application. /// </Summary> [STAThread] private static void Main () {// specify the full access permission for the corresponding directory for the user groupSetAccess ("Users", Application. StartupPath );// The System is in Chinese format. 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 dlg = new Login (); dlg. startPosition = FormStartPosition. centerScreen; if (DialogResult. OK = dlg. showDialog () {if (dlg. bLogin) {SplashScreen. splasher. show (typeof (SplashScreen. frmSplash); gc. mainDialog = new MainForm (); gc. mainDialog. startPosition = FormStartPosition. centerScreen; Application. run (gc. mainDialog) ;}} dlg. dispose ();}

In this way, after the program runs, we can see that the corresponding directory has full read and write permissions. This will solve some problems such as read and write SQLite errors.

The above is my summary of my experience in handling two different access permissions. I hope to give it to my peers in Winform development. Thank you for your patience and support.

 

Related Article

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.