首页 > 解决方案 > 无法加载文件或程序集“路径”或其依赖项之一。该系统找不到指定的文件

问题描述

我有服务。我尝试使用 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 文件存在于指定位置。为什么会出现这个错误?

编辑

第一次运行时此代码文件不存在并且会发生异常。那时我会将文件复制到指定位置并再次调用相同的代码。在第二次实际文件存在但显示相同的错误消息。

标签: c#windowsservice.net-assemblyassemblyinfo

解决方案


使用后AssemblyInstaller我们需要卸载文件。

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);

使用 aAppDomain我们可以卸载程序集。通过这个.exe文件运行后会被释放


推荐阅读