This question already has an answer here:
Uninstalling program
(1 answer)
Closed 4 years ago.
If I run the code below I'm pretty sure I'm supposed to get the Product Name and GUID (ex. App Path | {xxx}) for the application. But I'm only getting the path and no GUID is shown. Can someone help me?
// search in: LocalMachine_64
key = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall");
foreach (String keyName in key.GetSubKeyNames())
{
RegistryKey subkey = key.OpenSubKey(keyName);
displayName = Convert.ToString(subkey.GetValue("DisplayName"));
uninstlString = Convert.ToString(subkey.GetValue("UninstallString"));
if (p_name.Equals(displayName, StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine(subkey.GetValue("UninstallString"));
//string prdctId = uninstlString.Substring((uninstlString.IndexOf("{")));
string prdctId = uninstlString.Substring(12);
uninstallProcess.StartInfo.FileName = "MsiExec.exe";
uninstallProcess.StartInfo.Arguments = " /x " + prdctId + " /quiet /norestart";
uninstallProcess.StartInfo.UseShellExecute = true;
uninstallProcess.Start();
uninstallProcess.WaitForExit();
break;
//Console.WriteLine(subkey.GetValue("UninstallString"));
}
}
This is the image that I got running the code
I believe the UninstallString value is what gets executed when uninstalling an application via Add/Remove Programs. As your console output shows, it's the path to an executable.
The way you are retrieving the product ID...
string prdctId = uninstlString.Substring(12);
...therefore, is incorrect because you are taking a partial path. What you need to pass to MsiExec.exe /x is the product code, which is the registry key name itself, i.e....
string prdctId = keyName;
If you were invoking that command line from Command Prompt I'm pretty sure the curly brackets would necessitate putting quotes around the product code; I'm not sure if you'll need to do so when invoking the executable directly, but it can't hurt...
uninstallProcess.StartInfo.Arguments = " /x \"" + prdctId + "\" /quiet /norestart";
Related
I have a problem here and i need some help.
I work on a C# software in WPF, i have finished it, the program compile but do not run.
I've tried to search the problem using step by step run and it end on this line
var logfile = new NLog.Targets.FileTarget("logfile") { FileName = Application.StartupPath + #"\Logs\" + DateTime.Now.DayOfYear + ".txt" };
and
var logconsole = new NLog.Targets.ConsoleTarget("logconsole");
and i got this error : " Attempt to read or write protected memory. This often indicates that another memory is corrupted "
that happen randomly during execution but mostly while running theses lines of code.
If you got a solution i'll take it !
The WPF Application class does not have a StartupPath property.
You could add System.Windows.Forms as project reference and use System.Windows.Forms.Application.StartupPath
Alternative:
string appPath = System.Reflection.Assembly.GetExecutingAssembly()
.GetModules()[0].FullyQualifiedName;
string appDir = Path.GetDirectoryName(appPath);
To debug your code with finer granularity, you could rewrite it:
var fileName = Application.StartupPath;
fileName += #"\Logs\";
fileName += DateTime.Now.DayOfYear
fileName += ".txt";
var logfile = new NLog.Targets.FileTarget("logfile");
logFile.FileName = fileName;
I'm trying to uninstall a program with this code.. But it doesn't seem to work. I've tried the other answers but didn't seem to work either.. Can someone help me with this? I'm trying to uninstall the program by a given name(displayName)
For example I give the displayName = Appname then this code should uninstall the Appname program from my computer.
public static void UninstallApplictionInstalled(string p_name)
{
string displayName;
string uninstlString;
RegistryKey key;
ProcessStartInfo info = new ProcessStartInfo();
Process uninstallProcess = new Process();
string temp;
// search in: CurrentUser
key = Registry.CurrentUser.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall");
foreach (String keyName in key.GetSubKeyNames())
{
RegistryKey subkey = key.OpenSubKey(keyName);
displayName = Convert.ToString(subkey.GetValue("DisplayName"));
uninstlString = Convert.ToString(subkey.GetValue("UninstallString"));
if (p_name.Equals(displayName, StringComparison.OrdinalIgnoreCase) == true)
{
uninstallProcess.StartInfo.FileName = "MsiExec.exe";
uninstallProcess.StartInfo.Arguments = " /x " + uninstlString + " /quiet /norestart";
uninstallProcess.Start();
uninstallProcess.WaitForExit();
break;
//Console.WriteLine(subkey.GetValue("UninstallString"));
}
}
// search in: LocalMachine_32
key = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall");
foreach (String keyName in key.GetSubKeyNames())
{
RegistryKey subkey = key.OpenSubKey(keyName);
displayName = Convert.ToString(subkey.GetValue("DisplayName"));
uninstlString = Convert.ToString(subkey.GetValue("UninstallString"));
if (p_name.Equals(displayName, StringComparison.OrdinalIgnoreCase) == true)
{
uninstallProcess.StartInfo.FileName = "MsiExec.exe";
uninstallProcess.StartInfo.Arguments = " /x " + uninstlString + " /quiet /norestart";
uninstallProcess.Start();
uninstallProcess.WaitForExit();
break;
//Console.WriteLine(subkey.GetValue("UninstallString"));
}
}
// search in: LocalMachine_64
key = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall");
foreach (String keyName in key.GetSubKeyNames())
{
RegistryKey subkey = key.OpenSubKey(keyName);
displayName = Convert.ToString(subkey.GetValue("DisplayName"));
uninstlString = Convert.ToString(subkey.GetValue("UninstallString"));
if (p_name.Equals(displayName, StringComparison.OrdinalIgnoreCase) == true)
{
//string prdctId = uninstlString.Substring((uninstlString.IndexOf("{")));
uninstallProcess.StartInfo.FileName = "MsiExec.exe";
uninstallProcess.StartInfo.Arguments = " /x " + uninstlString + " /quiet /norestart";
uninstallProcess.Start();
uninstallProcess.WaitForExit();
break;
//Console.WriteLine(subkey.GetValue("UninstallString"));
}
}
}
Only this pops up..
Duplicates: Welcome to Stackoverflow. Just to mention to you that I see this question asked in at least 3 different flavors. We will have to close some of your questions since the duplication scatters replies and can waste a lot of time if people answer the (seemingly) unanswered duplicates.
In short: please don't post the same question several times. Here are the other questions:
MsiExec.exe product id uninstall
MSI installer option- uninstalling an application
C#: Using C# for this can be clunky - no matter how you do it. I would not push a command line to msiexec.exe, but go directly via the MSI API. This API can be accessed via Win32 functions or COM automation.
Uninstall Appraches for MSI: For your reference, there is a myriad of ways to kick of an MSI
uninstall:
Uninstalling an MSI file from the command line without using msiexec.
Section 14 from the link above shows how to uninstall using C++ - if that is an option. However:, there are changes in the Visual Studio 2017 templates again, so it might need a tune-up to work "out-of-the-box".
However, I would use the MSI API - as already stated - and I would recommend you go via the native Win32 functions and that you use DTF (Deployment Tools Foundation) which is part of the WiX toolkit. It is a .NET wrapper for the MSI API - which will save you a lot of boilerplate code, at the expense of having to deploy the DTF DLL: Microsoft.Deployment.WindowsInstaller.dll along with your product. I do not know if this is acceptable. I have code that does not depend on DTF if need be, but it is much longer.
Mock-up C# Sample. Project reference to Microsoft.Deployment.WindowsInstaller.dll needed. Then try the below code in a fresh C# .NET project. You can get that DLL by installing the WiX toolkit - the open source toolkit to create MSI files. After installation check in %ProgramFiles(x86)%\WiX Toolset v3.11\bin (adjust for WiX version - current as of September 2018).
Installer GUI: Important note first: the setup's UI level is set via the Installer.SetInternalUI function. If you run in silent mode, then you need to run the executable elevated for the uninstall to work properly, or an access exception occurs. When you run in Full GUI mode, you need to elevate the install yourself - provided you have the rights to do so.
Run Elevated: How to check for admin rights: Check if the current user is administrator.
using System;
using Microsoft.Deployment.WindowsInstaller;
namespace UninstallMsiViaDTF
{
class Program
{
static void Main(string[] args)
{
// Update this name to search for your product. This sample searches for "Orca"
var productcode = FindProductCode("orca");
try
{
if (String.IsNullOrEmpty(productcode)) { throw new ArgumentNullException("productcode"); }
// Note: Setting InstallUIOptions to silent will fail uninstall if uninstall requires elevation since UAC prompt then does not show up
Installer.SetInternalUI(InstallUIOptions.Full); // Set MSI GUI level (run this function elevated for silent mode)
Installer.ConfigureProduct(productcode, 0, InstallState.Absent, "REBOOT=\"ReallySuppress\"");
// Check: Installer.RebootInitiated and Installer.RebootRequired;
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
Console.ReadLine(); // Keep console open
}
// Find product code for product name. First match found wins
static string FindProductCode(string productname)
{
var productcode = String.Empty;
var productname = productname.ToLower();
foreach (ProductInstallation product in ProductInstallation.AllProducts)
{
if (product.ProductName.ToLower().Contains(productname))
{
productcode = product.ProductCode;
break;
}
}
return productcode;
}
}
}
string UserFolder = Session["Username"].ToString();
if (!Directory.Exists("~/MisReports/EmailAttachment/"+UserFolder))
{
Directory.CreateDirectory("~/MisReports/EmailAttachment/"+UserFolder);
}
filePathE = Server.MapPath("~/MisReports/EmailAttachment/" + UserFolder + "/");
filePathE = filePathE + a + ".pdf";
bool isExist = File.Exists(filePathE);
if (isExist)
{
File.Delete(filePathE);
}
report.ExportToDisk(ExportFormatType.PortableDocFormat, filePathE);
I get the error
Could not find a part of the path
if (!Directory.Exists("~/MisReports/EmailAttachment/"+UserFolder))
{
Directory.CreateDirectory("~/MisReports/EmailAttachment/"+UserFolder);
}
in this area code does not enter if check although that the folder has not been created
The ~ is probably not evaluated if you are running on Windows. Windows is not Unix. Read up on Path.Combine, Environment.GetFolderPath and Environment.SpecialFolder on MSDN. You should build a path with code like
string directoryName = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "MisReports/EmailAttachment", UserFolder);
I'm trying to write a simple program in C sharp that should Autostart when Windows boots and keep working. I have tried several methods, which did not work though. Any suggestions? Note: I'm a beginner.
I tried:
var thisPath = System.IO.Directory.GetCurrentDirectory();
RegistryKey regKey = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run", true);
string path = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
string name = Path.GetFileName(Application.ExecutablePath);
if (regKey == null) // Key not existing, we need to create the key.
{
Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run");
}
regKey.SetValue(name, (string)path, RegistryValueKind.String);
and also:
string startupFolder = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
WshShell shell = new WshShell();
string shortcutAddress = startupFolder + #"\Mylibraryxd.lnk";
IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutAddress);
shortcut.Description = "A startup shortcut. If you delete this shortcut from your computer, LaunchOnStartup.exe will not launch on Windows Startup"; // set the description of the shortcut
shortcut.WorkingDirectory = Application.StartupPath; /* working directory */
shortcut.TargetPath = Application.ExecutablePath; /* path of the executable */
shortcut.Save(); // save the shortcut
None of these worked properly, do you have any ideas? Thank you!!!
You can press Windows + R and write shell:startup. if you have the file you can drag and drop it there or just create a link. Everything in that folder automaticly starts as soon as the user is logged in. That means you don't have to link it in the code itself.
I need list of installed application on the computer and their path directory, and I find this:
//Registry path which has information of all the softwares installed on machine
string uninstallKey = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(uninstallKey))
{
foreach (string skName in rk.GetSubKeyNames())
{
using (RegistryKey sk = rk.OpenSubKey(skName))
{
// we have many attributes other than these which are useful.
Console.WriteLine(sk.GetValue("DisplayName") +
" " + sk.GetValue("DisplayVersion"));
}
}
}
How I get the path? I tried sk.GetValue("DisplayPath")but it not work.
Thanks!
Each software will have a different name for InstallLocation, if it will be there at all.
The one thing that will always be is UninstallString, which returns the path of the uninstaller (exe), which you can strip the directory from.
However, you should know that you will not get all installed programs there, if you go by HKEY_CURRENT_USER.
You should go via HKEY_LOCAL_MACHINE.
So, the code you are seeking is:
string uninstallExePath = sk.GetValue("UninstallString");
DirectoryInfo directory = new FileInfo(uninstallExePath).Directory;
string directoryPath = directory.FullName;
For get the path I find that: GetValue("InstallLocation")
It's work but for so many value it get 'null' or "".