0

The problem is, my .NET Windows Service (running under NT AUTHORITY\SYSTEM) creates a file in a folder inside ProgramData, and the windows application gets a System.UnauthorizedAccessException if it tries to overwrite it. Currently logged in user has an admin account, but the app doesn't start elevated (and I would like to avoid it).

If the service starts after the application, then the file is created by the UI app and it works fine. Is it possible to make a .NET Windows Service create a file which can be overwritten by a Windows app?

Lou
  • 4,244
  • 3
  • 33
  • 72

1 Answers1

1

It is just about file permissions. You need to add write entry for the users you want to be able to run the application. See this MSDN article on how to set it.

The key part:

// Get a FileSecurity object that represents the 
// current security settings.
FileSecurity fSecurity = File.GetAccessControl(fileName);

// Add the FileSystemAccessRule to the security settings.
fSecurity.AddAccessRule(new FileSystemAccessRule(account,
                rights, controlType));

// Set the new access settings.
File.SetAccessControl(fileName, fSecurity);
Michal Klouda
  • 14,263
  • 7
  • 53
  • 77
  • Thanks! This is helpful! But I tried to add access control to Everyone as [explained here](http://stackoverflow.com/a/6533772/1488067), and it fails inside my win app (service does it without problems). Should I only set permissions in the service app? – Lou Oct 15 '12 at 07:34
  • `System.UnauthorizedAccessException`: Attempted to perform an unauthorized operation, at `System.IO.File.SetAccessControl`. But the service does it without problems, and writing then works without problem. But since this code is shared between both apps, I guess I have to check who's running it before trying to set access control (it's only needed if win service is creating the file). Does that make sense? – Lou Oct 15 '12 at 08:01
  • It means that the user you run application under doesn't have sufficient rights to change file permissions. Then what you say will solve it. – Michal Klouda Oct 15 '12 at 08:03