我正在构建一个应用程序,只需点击一下按钮即可安装公司的所有定制软件。列表中包含资产跟踪器/报告工具,必须在启动时为每个人运行。我们的标准版本(我无法控制这一点)是Windows 10,我们还有一些传统的Windows 7机器,但在每种情况下,启动注册表项都被锁定,所以我开始在C:\ ProgramData \中创建快捷方式Microsoft \ Windows \ Start Menu \ Programs \ Startup。
如果启动文件夹不存在,则会创建该文件夹。以本地管理员身份登录,我可以手动创建启动文件夹而不会弹出UAC,获取文件夹的所有权并指定Everyone具有修改权限,在那里创建快捷方式。当我注销/开启时,软件会运行。但是,当我对此进行编码时,我会收到权限错误。
以下是代码:
Sub DetectFolders()
Dim sFolder1 As String = "C:\My Apps\"
Dim sFolder2 As String = "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\"
Dim sFolder3 As String = "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\"
If Not Directory.Exists(sFolder1) Then
Directory.CreateDirectory(sFolder1)
End If
If Not Directory.Exists(sFolder2) Then
Try
' create folder
TakeOwnership(sFolder3)
Application.DoEvents()
AddDirectorySecurity(sFolder3, "MyDomain\" & Environment.UserName, FileSystemRights.FullControl, AccessControlType.Allow)
Application.DoEvents()
Directory.CreateDirectory(sFolder2)
Application.DoEvents()
TakeOwnership(sFolder2)
' everyone has modify access // TEST
AddDirectorySecurity(sFolder2, "Everyone", FileSystemRights.Modify, AccessControlType.Allow)
Catch ex As Exception
MessageBox.Show(ex.Message, "Config", MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End Try
End If
End Sub
Sub TakeOwnership(ByVal sfolder As String)
' take ownership
Try
Dim ds As System.Security.AccessControl.DirectorySecurity
Dim account As System.Security.Principal.NTAccount
ds = System.IO.Directory.GetAccessControl(sfolder, System.Security.AccessControl.AccessControlSections.Owner)
account = New System.Security.Principal.NTAccount(System.Security.Principal.WindowsIdentity.GetCurrent.Name)
ds.SetOwner(account)
System.IO.Directory.SetAccessControl(sfolder, ds)
Application.DoEvents()
Catch ex As Exception
MessageBox.Show("" & ex.Message & "", "Take Ownership", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Sub AddDirectorySecurity(ByVal FileName As String, ByVal Account As String, ByVal Rights As FileSystemRights, ByVal ControlType As AccessControlType)
Try
' Create a new DirectoryInfoobject.
Dim dInfo As New DirectoryInfo(FileName)
' Get a DirectorySecurity object that represents the
' current security settings.
Dim dSecurity As DirectorySecurity = dInfo.GetAccessControl()
' Add the FileSystemAccessRule to the security settings.
dSecurity.AddAccessRule(New FileSystemAccessRule(Account, Rights, ControlType))
' Set the new access settings.
dInfo.SetAccessControl(dSecurity)
Catch ex As Exception
MessageBox.Show("" & ex.Message & "", "Add Security", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
出现的前两个错误是:尝试执行未经授权的操作,这是从第一次调用AddDirectorySecurity和TakeOwnership时生成的。
然后我得到一个错误,指出:
拒绝访问路径'C:\ ProgramData \ Microsoft \ Windows \ Start Menu \ Programs \ Startup'。
这是从DetectFolders sub
中的directory.createdirectory行生成的我很快就开始没有想法让这个工作了。这是我的代码中的东西吗?我错过了什么,或者Windows 10不能以这种方式工作。我们将非常感激地提供任何建设性的帮助。