Problem writing Mac hosts file

Hi,
I’m trying to read and edit the macOS hosts file into a TextArea.

Reading : works well slight_smile:

Dim t As TextInputStream
Dim f As FolderItem
Dim x as String
f = FolderItem.DriveAt(0).Child("private").Child("etc").Child("hosts")
if f<> nil then
  t = TextInputStream.Open(f)
  t.Encoding = Encodings.UTF8
  
  While Not t.EndOfFile
    x = t.ReadLine
    TextArea1.Text = TextArea1.Text + EndOfLine + x
  Wend
    t.Close
else
  //user cancelled
end

But, I have an error on writing the file :

Var f As FolderItem
Var t As TextOutputStream

f = FolderItem.DriveAt(0).Child("private").Child("etc").Child("hosts")
If f <> Nil Then
  Try
    t = TextOutputStream.Open(f). <-------- ERROR !
    t.Write(TextArea1.Text)
    t.Close
  Catch e As IOException
    // handle error
  End Try
End If

Thank you for your help !

Right. You have to have sudo rights to write to the hosts file.

As-tu la permission d’écriture pour ce fichier ?

Extrait du fichier:

Do not change this entry.

Battu sur la ligne d’arrivée…

The system won’t let you write to the file directly. It is placed in a reserved folder.

Perhaps what you can try is to copy the file to a folder where you write to it, then afterward copy the file back to Private/etc/.

With some luck, the system will simply require the user to enable the operation.

And who knows why Apple caution writing…

You still need to be sudo to copy it back it’s permissions are

rw-r--r--  root:wheel 

Because all system files are off limit to regular users. It is the same under Windows.

“Perhaps what you can try is to copy the file to a folder where you write to it, then afterward copy the file back to Private/etc/.”

Yes it seems to me to be a good workaround…

Unfortunately not, because as Greg has already said, you still won’t have the correct write permissions to copy the file back to the location. If you check the error number on the IOException that is triggered, you will probably see that it is 13, which is a write permissions error.

You are right, the error number on the IOException is 13 !
So how do I get write permission? by modifying the rights’s file with a “chmode” command?

See Monkeybread Xojo plugin - AuthorizationMBS class . There is a newer class where I always forget the name.

Thanks for infos. We’ll ask @Christian_Schmitz.