原始代码如下:
public static bool UnintService(String serverName, string exeName)
{
try
{
//UnInstall Service
if (CheckService(serverName))
{
var myAssemblyInstaller = new AssemblyInstaller
{
UseNewContext = true,
Path = System.Environment.CurrentDirectory + "\\" + exeName
};
myAssemblyInstaller.Uninstall(null);
myAssemblyInstaller.Dispose();
myAssemblyInstaller = null;
return true;
}
else
{
return true;
}
}
catch (Exception ex)
{
throw new Exception("unInstallServiceError/n" + ex.Message);
return false;
}
}
发现我再执行完这个卸载步骤后,想通过本身这个程序,删掉服务对应的exe文件,就会报该文件被占用,无法删除。
被这个问题困扰了很长时间,具体原因不明,目前通过一个new
AppDomain删除后,再关闭该AppDomain解决。代码如下:
public static bool UnintService(String serverName, string exeName)
{
try
{
//UnInstall Service
if (CheckService(serverName))
{
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[] { System.Environment.CurrentDirectory + "\\" + exeName, new String[] { } }, null, null, null).Unwrap() as AssemblyInstaller)
{
installer.UseNewContext = true;
installer.Uninstall(null);
installer.Dispose();
}
AppDomain.Unload(domain);
return true;
}
else
{
return true;
}
}
catch (Exception ex)
{
throw new Exception("unInstallServiceError/n" + ex.Message);
}
}