windows 安装程序无法访问目录

windows installer cannot access directory

我正在尝试 运行 使用 windows 服务安装程序为 windows 服务(该服务是 LocalSystem 帐户)的一些自定义操作代码,但我收到以下错误消息:

安装 MSI 时出现错误消息:

Error 1001. An Exception occurred in the OnAfterInstall event handler
of System.ServiceProcess.ServiceInstaller. --> Access to the path XXX
is denied. 

此代码引发错误:

protected override void OnAfterInstall(IDictionary savedState)
{
      string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
      System.IO.File.WriteAllText(path, "test");
}

在代码中,我试图访问服务 .exe 目录,以便我可以删除在那里创建的文件

我的目标是为 install/uninstalling 流程制作自定义操作。我想删除安装后创建的文件,如日志和配置文件。

谢谢

您正在尝试将文本写入目录而不是文件。变量 "path" 从 Path.GetDirectoryName() 返回,这是一个目录。在下一行中,您正尝试对该变量执行 File.WriteAllText(),因此出现错误。

Path.Combine: As already mentioned by others, you need to specify a proper full path (path and file name). Maybe use Path.Combine? For example:

 System.IO.File.WriteAllText(Path.Combine(path, "filename.txt"), "test");

备选方案:我不是 .NET 专家,也不使用托管代码自定义操作。但是,如果它们是基于 DTF 的,我不确定它们是否有关于当前目录或执行目录的任何问题。列出一些进一步的链接:

  • 添加注释:Environment.SpecialFolder(获取各种特殊文件夹)和Environment.CurrentDirectory(获取当前目录)。
  • 反思可能会更好,但请检查这个答案:How to get execution directory of console application (all answers). There is also: AppDomain.CurrentDomain.BaseDirectory: Getting the absolute path of the executable, using C#?
  • 然后有建议使用GetEntryAssemblyC# – Getting the Directory of a Running Executable.
  • Directory.GetCurrentDirectory Method.