我有服务。我尝试使用C#安装它。即使存在服务文件,我也会收到错误消息Could not load file or assembly 'file:///C:\Sample\sample.exe' or one of its dependencies. The system cannot find the file specified.
我使用installutil进行安装,成功了。
string Path = @"C:\sample\sample.exe";
string[] commandLineOptions = new string[1] { "/LogFile=install.log" };
using (AssemblyInstaller installer = new AssemblyInstaller(Path, commandLineOptions))
{
installer.UseNewContext = true;
installer.Install(null);
installer.Commit(null);
}
此代码产生错误与installutil相同的路径成功。我检查了路径,在指定位置存在sample.exe文件。为什么会发生此错误?
编辑
第一次运行时不存在此代码文件,并且会发生异常。到那时,我会将文件复制到指定的位置,并再次调用相同的代码。在第二次实际文件存在但显示相同的错误消息。
var domain = AppDomain.CreateDomain("MyDomain");
using (AssemblyInstaller installer = domain.CreateInstance(typeof(AssemblyInstaller).Assembly.FullName, typeof(AssemblyInstaller).FullName, false, BindingFlags.Public | BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.ExactBinding, null, new Object[] { Path, new String[] { } }, null, null, null).Unwrap() as AssemblyInstaller)
{
installer.UseNewContext = true;
installer.Install(null);
installer.Commit(null);
}
AppDomain.Unload(domain);
使用AppDomain
,我们可以卸载程序集。通过该.exe文件将在操作后释放