Search code examples
c#wixsharp

ProgramData environment variable not recognized wixsharp


I tried to delete a folder at uninstall but it does nothing. specifying the path though, get it to work. Not working:

 public void OnAfterInstall(SetupEventArgs e)
        {
            if (e.IsUninstalling)
            {
                
                DirectoryInfo dir = new DirectoryInfo(@"CommonAppDataFolder\myFolder");
                if ((bool)(dir?.Exists))
                {
                    dir?.Delete(true);
                }
                
            }
        }

Working:

public void OnAfterInstall(SetupEventArgs e)
        {
            if (e.IsUninstalling)
            {
                
                DirectoryInfo dir = new DirectoryInfo(@"C:\ProgramData\myFolder");
                if ((bool)(dir?.Exists))
                {
                    dir?.Delete(true);
                }
                
            }
        }

Edit: I tried this code and I'm getting the very same error:

        var programFiles = Environment.ExpandEnvironmentVariables("%ProgramFiles%");
        var manifestFile = Path.Combine(programFiles,@"\My Company\myFile.man");

        FileInfo fInfo = new FileInfo(manifestFile);
        if ((bool)(fInfo?.Exists))
        {
            FileSecurity security = fInfo.GetAccessControl();
            security.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null),
                FileSystemRights.ReadAndExecute, AccessControlType.Allow));
            fInfo.SetAccessControl(security);
        }

        var CMDCommand = $@"/C wevtutil im {manifestFile}";
        Process.Start("CMD.exe", CMDCommand);

I tried also this:

var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
    var manifestFile = programFiles + @"\My Company\myFile.man";

Running this code on C:\ is working fine..


Solution

  • You should expand the environment variable to get the actual path

    var common = Environment.ExpandEnvironmentVariables("%ProgramData%");
    var yourFolder = Path.Combine(common, "myFolder");
    DirectoryInfo dir = new DirectoryInfo(yourFolder);
    

    Notice how to to retrieve an Environment Variable from its string you need to put the string between %, also you could get an Hashtable with all the Environment Variables defined on your machine (custom or standard) using

    var envs = Environment.GetEnvironmentVariables();
    

    Consider also the alternative (or probably a better choice) highlighted by Hans Passant in its comment. Environment.GetFolderPath is a method that receives an enum SpecialFolder and returns the path for the special folder requested.

    This is a better choice because it not depends on an Environment Variable that could be changed o removed and thus creating a possible buggy situation.

    var common = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);