vb.netpermissionsautocadprogram-files

Edit Settings.txt Document within Program Files directory during AutoCAD runtime


I am trying to store the AutoCAD users' settings in a directory under their Program Files. Originally, I had everything stored in the users favorites folder, but I wanted to keep all the plugin documents/files within the same directory. So, I have been trying all kinds of options to get admin rights during runtime, but still have not been successful. This is, more or less, what I just recently tested:

Public Shared Sub GetAdminAccess()
    AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal)
    Dim curIdentity As WindowsIdentity = WindowsIdentity.GetCurrent()
    Dim principalPerm As PrincipalPermission = New PrincipalPermission(Nothing, "BUILTIN\Administrators")
    principalPerm.Demand()
End Sub

<PrincipalPermissionAttribute(SecurityAction.Demand, Role:="BUILTIN\Administrators")>
Private Shared Sub CreateSettingsFile()
    Try
        IO.File.Create(SettingsFilePath)
        SettingsFileData = DefaultFileData
        Property_WindowsOnTop = True
        Property_SaveBackups = False
        Property_SkipCreateSite = False
        Property_AlignmentZoomExtents = ToFullExtents
        Property_SaveBackups_Method = _TxtValue_Generic_None
        Property_SaveBackups_MainDirectoryPath = _TxtValue_Generic_None
        Call SetUserSettings(SettingsFileData)
        Call SetPropertySettings()
    Catch IOE As IO.IOException
        MsgBox(IOE.Message)
    Catch Ex As Exception
        MsgBox(Ex.Message)
    End Try
End Sub

Many of my attempts have resulted with this same error:

"Application attempted to perform an operation now allowed by the security policy. To grant this application the required permission, contact your system administrator, or use the Microsoft.NET Framework Configuration tool.

If you click Continue, the application will ignore this error and attempt to continue.

Request for principal permission failed."


Solution

  • An app can't write to the Program Files folder without administrator rights. The program files folder (and subfolders under it) are admin protected to prevent programs from replacing installed executable code with a malicious equivalent. Just don't do that.

    If want app-specific data, use the appData folder. You can access that folder using System.Environment.SpecialFolder.ApplicationData and Environment.GetFolderPath

    Get comfortable with the SpecialFolder enumeration (and with System.IO.Path.Combine). They are the correct way to access all of the well-known folders in the Windows OS.