I have an application where I would like users to be able to perform an SQL/Server backup to their home directory. Because SQL is running under the Network Service account it gives a file system permission error when attempting the backup. I’ve tried the following code and a few variants to try giving full control to the network account:
Public Sub GiveFolderNetworkAccess(FilePath As String)
Dim SID As SecurityIdentifier = New SecurityIdentifier(WellKnownSidType.NetworkServiceSid, Nothing)
Dim FolderInfo As IO.DirectoryInfo = New IO.DirectoryInfo(FilePath)
Dim FolderAcl As New DirectorySecurity
FolderAcl.AddAccessRule(New FileSystemAccessRule(SID, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit Or InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow))
FolderInfo.SetAccessControl(FolderAcl)
End Sub
Hower I get a System.UnauthorizedAccessException exception when calling FolderInfo.SetAccessControl. I’ve also tried the code on non-Windows paths where the user has full control and get the same result. Any ideas appreciated, I’m currently testing this under Windows 7 and .NET Framework 4.
Many thanks to OwerFlov for his suggestion that setting the permissions on a folder would require elevation even if the user had permission on the folder, that indeed turned out to be the case. For the specific application I decided to create a backup directory using InstallShield with appropriate permissions and then copy the SQL/Server backup file to the final destination. I used compression so the extra file access was required anyway.
I’ve since had a chance to research further and found that changing access on a specific file does not require elevation. For any similar future requirements I’ve written the following code that creates an empty file with full control permission granted to the Network Service account:
Doing some testing SQL/Server will successfully overwrites an empty file with the backup set.