【发布时间】:2021-11-08 11:38:59
【问题描述】:
我正在使用 TaskScheduler 在部署期间设置计划任务。同时我正在使用设置文件来存储用户配置。现在,当任务调度程序运行时,它不会访问设置文件,因为用户不匹配。
在安装过程中,安装项目作为系统运行以获得在应用程序目录中的写入权限。我正在运行自定义操作来编写设置和计划任务,但用户不匹配。
如何确保用户匹配。我是否必须创建一个单独的应用程序来进行配置,以便设置可以在应用程序范围内?这对我来说毫无意义,因为这些设置在每次部署时都会有所不同,并且是由用户而不是我设置的。
编辑:用户设置文件的位置
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "ApplicationName");
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
Directory.SetCurrentDirectory(path);
脚本片段创建计划任务
using Microsoft.Win32.TaskScheduler;
...
if (Interval == null) Interval = TimeSpan.FromHours(1);
if (Duration == null) Duration = TimeSpan.FromDays(1);
using(TaskService ts = new TaskService())
{
var td = ts.NewTask();
// attempt to get the correct user, gets system user as if ommitted
td.Principal.UserId = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
td.Principal.LogonType = TaskLogonType.InteractiveToken;
td.Settings.ExecutionTimeLimit = TimeSpan.FromMinutes(5);
var trigger = new DailyTrigger((short)DaysInterval)
{
StartBoundary = DateTime.Today,
Repetition = new RepetitionPattern(Interval, Duration)
};
td.Triggers.Add(trigger);
string exePath = System.Reflection.Assembly.GetEntryAssembly().Location;
td.Actions.Add("\"" + exePath + "\"", "", Path.GetDirectoryName(exePath));
ts.RootFolder.RegisterTaskDefinition("myTask", td);
}
自定义操作,可以这么说是太大了,在项目的不同文件中拆分以在此处共享
编辑:设置文件的设置字段示例
Properties.Settings _s = Properties.Settings.Default;
_s.ClientIp = Tx_Ip.Text;
_s.ShopID = Tx_ShopId.Text;
_s.Save();
编辑:我现在已经在安装期间和通过计划任务运行时记录了用户、用户路径和应用路径。
设置
User: NT-AUTORITÄT\SYSTEM
UserPath: C:\Users\user\AppData\Local\appname
AppPath: C:\Program Files (x86)\businessname\appname
计划任务
User: NT-AUTORITÄT\SYSTEM
UserPath: C:\Windows\system32\config\systemprofile\AppData\Local\appname
AppPath: C:\Program Files (x86)\businessname\appname
所以实际上它是同一个用户,但用户路径不同。当我在设置期间编写设置时,它们被保存在错误的位置,以后在计划任务期间无法访问。
【问题讨论】:
-
用户设置文件在哪里?你如何使用它?如果可能,共享编写两者的自定义操作的代码。
-
我已经添加了请求的代码@iamdlm
标签: c# .net installation scheduled-tasks settings