I want to call diskpart.exe from my application (C# .net 4.8) to delete and reinitialize an attached storage device.
However, the user needs administration rights to do this.
However, I do not want to store an admin user with password in the application.
Is it somehow possible to authorize my program once to call diskpart.exe at any time?
I have already read on the internet that it is possible via a Windows Service or a Scheduled Task. However, both approaches have not worked for me so far.
What you can do is query the admin rights for your application at startup, see this answer on how to do that (add
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
to your application manifest).Of course, that requires that the user gives consent to run your application (or provides an admin password at startup), but if your c# application runs as admin, it will be possible to start other applications requiring admin permissions (such as diskpart) to run without further queries.
The hint with the task scheduler won't work so easily, because configuring the task scheduler for certain actions will also require admin rights. The only thing you could try is prepare a task during application installation (as admin) and then start that task later as non-admin. That could work.