I finally found the solution to this thanks to @SushiHangover's suggestions which led to the following post: https://forums.xamarin.com/discussion/103039/xamarin-mac-multiple-do-shell-script-with-administrator-privilege-with-one-password-request
Instead of using the System.IO.File
static methods to write to the hosts file directly, I instead write to a temporary file. I then launch the cat
command to overwrite the contents of the hosts file with the contents of the temp file by using the ExecuteWithPrivileges
method. This brings up the Mac default prompt for the users password and the cat
command is executed as sudo.
private static void WriteToHostsFile(IEnumerable<HostEntry> hostEntries, IHostsFileWriter hostsWriter)
{
var hostsText = hostsWriter.GetHostsFileText(hostEntries);
var fi = new FileInfo("hoststemp.txt");
File.WriteAllText("hoststemp.txt", hostsText);
var defaults = Security.AuthorizationFlags.Defaults;
using (var auth = Security.Authorization.Create(defaults))
{
auth.ExecuteWithPrivileges("/bin/cat", defaults, new[] { fi.FullName + " > /etc/hosts" });
}
}
It should be noted that this method has been marked as deprecated in favor of SMJobBless: https://developer.apple.com/library/archive/samplecode/SMJobBless/Introduction/Intro.html
I haven't managed to work that out in Xamarin yet though, and looks quite involved for the small task I needed to do.