4

So, I'm doing a setup project, all written in VB.NET, and I need to give to the NetworkService account, permission on a certain folder.

The following code works perfect (Windows 7 - en-US):

Dim dInfo As New DirectoryInfo("C:\FolderOrFileToGivePermission")
Dim dSecurity As DirectorySecurity = dInfo.GetAccessControl()
dSecurity.AddAccessRule(New FileSystemAccessRule("NETWORK SERVICE", FileSystemRights.FullControl, AccessControlType.Allow))
dInfo.SetAccessControl(dSecurity)

The problem began when I try this very same code on my Windows 7, Vista or XP (all in PT-BR) , I found that there is no "NETWORK SERVICE", the correct name is "Serviço de Rede".

I need to get this name to give permission to the right user.

After a lot of investigation on all 3 OSes, I found that the ID for the user is: "S-1-5-20", his path on the registry is: Computer\HKEY_USERS\S-1-5-20 and the default folder for it: C:\Windows\ServiceProfiles\NetworkService

But I still didn't find the actual "localizable" name and I need it to be dynamic, because this system will be installed in a lot of different countries (different machines and cultures).

Thanks in advance.

Izzy Rodriguez
  • 2,097
  • 3
  • 21
  • 32

2 Answers2

6

Use the System.Security.Principal.WellKnownSidType enumeration:

SecurityIdentifier networkService = new SecurityIdentifier(
    WellKnownSidType.NetworkServiceSid, null);

FileSystemAccessRule rule = new FileSystemAccessRule(
    networkService, FileSystemRights.FullControl, AccessControlType.Allow);
Joe Daley
  • 45,356
  • 15
  • 65
  • 64
  • It seems like a cleaner and better solution, unfortunately I do not work on the company anymore, and I can't test it on the project. – Izzy Rodriguez May 07 '12 at 20:01
1

So, after more and more research, I've changed my search over Google and stackoverflow, and I've found the answer on another question:

The best way to resolve display username by SID?

Dim NetworkServiceName as String = new SecurityIdentifier("S-1-5-20").Translate(typeof(NTAccount)).ToString();
Community
  • 1
  • 1
Izzy Rodriguez
  • 2,097
  • 3
  • 21
  • 32
  • I'm just curious if you used "NT AUTHORITY\NetworkService" instead of "NETWORK SERVICE" would it work. – Chris Haas Mar 30 '10 at 15:42
  • I've tried on Vista pt-BR before posting the question and didn't worked, aparently because "NT AUTHORITY" is "AUTORIDADE NT" on pt-BR – Izzy Rodriguez Mar 30 '10 at 18:21