tags:

views:

56

answers:

0

Trying to delete an existing file and write a new on network share, Get the following exception..

[4804] System.UnauthorizedAccessException: Attempted to perform an unauthorized operation. 
[4804]    at System.Security.AccessControl.Win32.GetSecurityInfo(ResourceType resourceType, String name, SafeHandle handle, AccessControlSections accessControlSections, RawSecurityDescriptor& resultSd) 
[4804]    at System.Security.AccessControl.NativeObjectSecurity.CreateInternal(ResourceType resourceType, Boolean isContainer, String name, SafeHandle handle, AccessControlSections includeSections, Boolean createByName, ExceptionFromErrorCode exceptionFromErrorCode, Object exceptionContext) 
[4804]    at System.Security.AccessControl.FileSystemSecurity..ctor(Boolean isContainer, String name, AccessControlSections includeSections, Boolean isDirectory) 
[4804]    at System.Security.AccessControl.DirectorySecurity..ctor(String name, AccessControlSections includeSections) 
[4804]    at System.IO.DirectoryInfo.GetAccessControl(AccessControlSections includeSections) `enter code here`
[4804]    at Excel.SetAcl(String filename, String account) in D:\SAABZX01D\dev\libraries\EXCEL\Class1.cs:line 228 
[4804]    at Excel.doKEStats(String baanId, String fromDate, String toDate) in D:\SAABZX01D\dev\libraries\EXCEL\Class1.cs:line 87 

Here is my code

public static  bool SetAcl(string filename,string account)
{
    FileSystemAccessRule rule = new FileSystemAccessRule(account, FileSystemRights.FullControl, AccessControlType.Allow);
     string path= System.IO.Directory.GetDirectoryRoot(filename);
  System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(filename);


  bool what = false;
  DirectorySecurity security = di.GetAccessControl(AccessControlSections.Access);
  security.ModifyAccessRule(AccessControlModification.Add, rule, out what);




  di.SetAccessControl(security);
  return what;

}

btw This works fine when run as a console app but would work when called from external process (SQL server xp_cmdshell)