使用AssemblyInstaller卸載服務後,卸載程序不關閉,就無法刪除服務對應的exe的問題

原始代碼如下:

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章