Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

osx - How to programmatically delete a file with elevated privileges?

I'm trying to remove a file form the ~/Library/PreferencePanes folder, and this cannot be done with normal privileges. Usually, if you need to delete any file from the ~/Library folder the system will ask for your username and password.

The current way I do this is with

[[NSFileManager defaultManager] removeItemAtPath:filePath error:&error]

but this keeps on returning an error ([error localizedDescription]):

theAppName.prefPane couldn’t be removed because you don’t have permission to access it.

What logic and code would I need to use in order to gain these elevated privileges needed for deleting files?

Thanks!

like image 231
Alex Avatar asked Jun 07 '11 14:06

Alex


People also ask

How do you delete a file that says I don't have permission Mac?

You don't have permission to delete the file Control-Click them and select Get Info for them and then scroll down the window that opens to the section headed “Sharing and Permissions”. In this menu make sure that the user you're currently signed in as has permission to read and write these files.

How do I make sure a file is permanently deleted on Mac?

To permanently delete a file or folder, bypassing the Trash, press Option + Command + Delete keys. To remove a file a folder to the Trash, press Command + Delete keys. To empty your Trash, use Command + Option + Shift + Delete.


2 Answers

You should go through the Authorization Services Programming Guide. You will need to use AuthorizationExecuteWithPrivileges.

like image 97
Deepak Danduprolu Avatar answered Oct 17 '22 01:10

Deepak Danduprolu


The only method I could find and which worked for me was to create a command line tool in Xcode. Install the tool as a Launchd Job using SMJOBBLESS and then use XPC connection to talk to it. Follow the below EvenBetterAuthorization sample to understand how all of the above works.

https://developer.apple.com/library/mac/samplecode/EvenBetterAuthorizationSample/Listings/Read_Me_About_EvenBetterAuthorizationSample_txt.html#//apple_ref/doc/uid/DTS40013768-Read_Me_About_EvenBetterAuthorizationSample_txt-DontLinkElementID_17

like image 24
Vinod Madigeri Avatar answered Oct 17 '22 00:10

Vinod Madigeri