0

I'm building a Setup Project so I can ship my WinUI/WPF application. In said applicaiton I use some NuGet packages that creat files on the executable's location (folder) -- these are for MSAL and WebView2. However, Windows sets only Read access to folders on the Program Files folder, so I wanted to create a custom action that gives write permission to the folder throughout the installation.

Most solutions out there are extremely outdated (.NET framework dependent) or tangents to the overall problem.

I have tried creating a Console Application, writing the following code, shipping it as a DLL/EXE and adding it as a Custom Action. My application installed but still did not have write permissions.

   static void Main(string[] args)
   {
        string directory = args[0];
        DirectoryInfo directoryInfo = new DirectoryInfo(directory);

        // This gets the "Authenticated Users" group, no matter what it's called
        SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);

        // Create the rules
        FileSystemAccessRule writerule = new FileSystemAccessRule(sid, FileSystemRights.Write, AccessControlType.Allow);

        if (!string.IsNullOrEmpty(directory) && Directory.Exists(directory))
        {
            // Get your file's ACL
            DirectorySecurity fsecurity = FileSystemAclExtensions.GetAccessControl(directoryInfo);

            // Add the new rule to the ACL
            fsecurity.AddAccessRule(writerule);

            // Set the ACL back to the file
            FileSystemAclExtensions.SetAccessControl(directoryInfo, fsecurity);
        }
    }

This code was based on the following thread: https://stackoverflow.com/a/10540927/16751261

  • 2
    I know you don't want to hear this, but it is bad practice / security vulnerability making anything in Program Files writable. If your app requires creation of files during runtime the best practice is to use the %localappdata% directory which is specifically for this case and users are guaranteed to have access to it. Your solution then would be to make changes to read and write to/from %localappdata%. – DSander Dec 23 '22 at 22:41
  • 1
    If interested I can give you some pointers to setting up the UDF for WebView2. https://learn.microsoft.com/en-us/microsoft-edge/webview2/concepts/user-data-folder?tabs=dotnet WebView2 devs all agree that the default location is only for development/testing and not for production release. You should change to a custom UDF location which is usually something like %localappdata%/MyAppName – DSander Dec 23 '22 at 22:52
  • Thank you for that; it made me fix the problem another way. I still would like to know how it could be done, even though I wouldn't necessarily use it for production anymore. There's value in understanding how Custom Actions work. Anyways, thank you for that! Best, Paulo. – rossir.paulo Dec 25 '22 at 21:36

0 Answers0